home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / Firefox Setup 3.0.6.exe / nonlocalized / components / nsExtensionManager.js < prev    next >
Encoding:
Text File  |  2009-01-19  |  325.7 KB  |  8,862 lines

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /*
  3. //@line 44 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  4. */
  5.  
  6. //
  7. // TODO:
  8. // - better logging
  9. //
  10.  
  11. const Cc = Components.classes;
  12. const Ci = Components.interfaces;
  13. const Cr = Components.results;
  14.  
  15. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  16.  
  17. const PREF_EM_CHECK_COMPATIBILITY     = "extensions.checkCompatibility";
  18. const PREF_EM_CHECK_UPDATE_SECURITY   = "extensions.checkUpdateSecurity";
  19. const PREF_EM_LAST_APP_VERSION        = "extensions.lastAppVersion";
  20. const PREF_EM_ENABLED_ITEMS           = "extensions.enabledItems";
  21. const PREF_UPDATE_COUNT               = "extensions.update.count";
  22. const PREF_UPDATE_DEFAULT_URL         = "extensions.update.url";
  23. const PREF_EM_NEW_ADDONS_LIST         = "extensions.newAddons";
  24. const PREF_EM_IGNOREMTIMECHANGES      = "extensions.ignoreMTimeChanges";
  25. const PREF_EM_DISABLEDOBSOLETE        = "extensions.disabledObsolete";
  26. const PREF_EM_EXTENSION_FORMAT        = "extensions.%UUID%.";
  27. const PREF_EM_ITEM_UPDATE_ENABLED     = "extensions.%UUID%.update.enabled";
  28. const PREF_EM_UPDATE_ENABLED          = "extensions.update.enabled";
  29. const PREF_EM_ITEM_UPDATE_URL         = "extensions.%UUID%.update.url";
  30. const PREF_EM_DSS_ENABLED             = "extensions.dss.enabled";
  31. const PREF_DSS_SWITCHPENDING          = "extensions.dss.switchPending";
  32. const PREF_DSS_SKIN_TO_SELECT         = "extensions.lastSelectedSkin";
  33. const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin";
  34. const PREF_EM_LOGGING_ENABLED         = "extensions.logging.enabled";
  35. const PREF_EM_UPDATE_INTERVAL         = "extensions.update.interval";
  36. const PREF_UPDATE_NOTIFYUSER          = "extensions.update.notifyUser";
  37. const PREF_MATCH_OS_LOCALE            = "intl.locale.matchOS";
  38. const PREF_SELECTED_LOCALE            = "general.useragent.locale";
  39.  
  40. const DIR_EXTENSIONS                  = "extensions";
  41. const DIR_CHROME                      = "chrome";
  42. const DIR_STAGE                       = "staged-xpis";
  43. const FILE_EXTENSIONS                 = "extensions.rdf";
  44. const FILE_EXTENSION_MANIFEST         = "extensions.ini";
  45. const FILE_EXTENSIONS_STARTUP_CACHE   = "extensions.cache";
  46. const FILE_EXTENSIONS_LOG             = "extensions.log";
  47. const FILE_AUTOREG                    = ".autoreg";
  48. const FILE_INSTALL_MANIFEST           = "install.rdf";
  49. const FILE_CONTENTS_MANIFEST          = "contents.rdf";
  50. const FILE_CHROME_MANIFEST            = "chrome.manifest";
  51.  
  52. const UNKNOWN_XPCOM_ABI               = "unknownABI";
  53.  
  54. const FILE_DEFAULT_THEME_JAR          = "classic.jar";
  55. const TOOLKIT_ID                      = "toolkit@mozilla.org"
  56.  
  57. const KEY_PROFILEDIR                  = "ProfD";
  58. const KEY_PROFILEDS                   = "ProfDS";
  59. const KEY_APPDIR                      = "XCurProcD";
  60. const KEY_TEMPDIR                     = "TmpD";
  61.  
  62. const EM_ACTION_REQUESTED_TOPIC       = "em-action-requested";
  63. const EM_ITEM_INSTALLED               = "item-installed";
  64. const EM_ITEM_UPGRADED                = "item-upgraded";
  65. const EM_ITEM_UNINSTALLED             = "item-uninstalled";
  66. const EM_ITEM_ENABLED                 = "item-enabled";
  67. const EM_ITEM_DISABLED                = "item-disabled";
  68. const EM_ITEM_CANCEL                  = "item-cancel-action";
  69.  
  70. const OP_NONE                         = "";
  71. const OP_NEEDS_INSTALL                = "needs-install";
  72. const OP_NEEDS_UPGRADE                = "needs-upgrade";
  73. const OP_NEEDS_UNINSTALL              = "needs-uninstall";
  74. const OP_NEEDS_ENABLE                 = "needs-enable";
  75. const OP_NEEDS_DISABLE                = "needs-disable";
  76.  
  77. const KEY_APP_PROFILE                 = "app-profile";
  78. const KEY_APP_GLOBAL                  = "app-global";
  79. const KEY_APP_SYSTEM_LOCAL            = "app-system-local";
  80. const KEY_APP_SYSTEM_SHARE            = "app-system-share";
  81. const KEY_APP_SYSTEM_USER             = "app-system-user";
  82.  
  83. const CATEGORY_INSTALL_LOCATIONS      = "extension-install-locations";
  84. const CATEGORY_UPDATE_PARAMS          = "extension-update-params";
  85.  
  86. const PREFIX_NS_EM                    = "http://www.mozilla.org/2004/em-rdf#";
  87. const PREFIX_NS_CHROME                = "http://www.mozilla.org/rdf/chrome#";
  88. const PREFIX_ITEM_URI                 = "urn:mozilla:item:";
  89. const PREFIX_EXTENSION                = "urn:mozilla:extension:";
  90. const PREFIX_THEME                    = "urn:mozilla:theme:";
  91. const RDFURI_INSTALL_MANIFEST_ROOT    = "urn:mozilla:install-manifest";
  92. const RDFURI_ITEM_ROOT                = "urn:mozilla:item:root"
  93. const RDFURI_DEFAULT_THEME            = "urn:mozilla:item:{972ce4c6-7e08-4474-a285-3208198ce6fd}";
  94. const XMLURI_PARSE_ERROR              = "http://www.mozilla.org/newlayout/xml/parsererror.xml"
  95.  
  96. const URI_GENERIC_ICON_XPINSTALL      = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
  97. const URI_GENERIC_ICON_THEME          = "chrome://mozapps/skin/extensions/themeGeneric.png";
  98. const URI_XPINSTALL_CONFIRM_DIALOG    = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
  99. const URI_EXTENSIONS_PROPERTIES       = "chrome://mozapps/locale/extensions/extensions.properties";
  100. const URI_BRAND_PROPERTIES            = "chrome://branding/locale/brand.properties";
  101. const URI_DOWNLOADS_PROPERTIES        = "chrome://mozapps/locale/downloads/downloads.properties";
  102. const URI_EXTENSION_UPDATE_DIALOG     = "chrome://mozapps/content/extensions/update.xul";
  103. const URI_EXTENSION_LIST_DIALOG       = "chrome://mozapps/content/extensions/list.xul";
  104.  
  105. const INSTALLERROR_SUCCESS               = 0;
  106. const INSTALLERROR_INVALID_VERSION       = -1;
  107. const INSTALLERROR_INVALID_GUID          = -2;
  108. const INSTALLERROR_INCOMPATIBLE_VERSION  = -3;
  109. const INSTALLERROR_PHONED_HOME           = -4;
  110. const INSTALLERROR_INCOMPATIBLE_PLATFORM = -5;
  111. const INSTALLERROR_BLOCKLISTED           = -6;
  112. const INSTALLERROR_INSECURE_UPDATE       = -7;
  113. const INSTALLERROR_INVALID_MANIFEST      = -8;
  114. const INSTALLERROR_RESTRICTED            = -9;
  115.  
  116. const MODE_RDONLY   = 0x01;
  117. const MODE_WRONLY   = 0x02;
  118. const MODE_CREATE   = 0x08;
  119. const MODE_APPEND   = 0x10;
  120. const MODE_TRUNCATE = 0x20;
  121.  
  122. const PERMS_FILE      = 0644;
  123. const PERMS_DIRECTORY = 0755;
  124.  
  125. var gApp  = null;
  126. var gPref = null;
  127. var gRDF  = null;
  128. var gOS   = null;
  129. var gBlocklist            = null;
  130. var gXPCOMABI             = null;
  131. var gOSTarget             = null;
  132. var gConsole              = null;
  133. var gInstallManifestRoot  = null;
  134. var gVersionChecker       = null;
  135. var gLoggingEnabled       = null;
  136. var gCheckCompatibility   = true;
  137. var gCheckUpdateSecurity  = true;
  138. var gLocale               = "en-US";
  139. var gFirstRun             = false;
  140. var gAllowFlush           = true;
  141. var gDSNeedsFlush         = false;
  142. var gManifestNeedsFlush   = false;
  143.  
  144. /**
  145.  * Valid GUIDs fit this pattern.
  146.  */
  147. var gIDTest = /^(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)$/i;
  148.  
  149. // shared code for suppressing bad cert dialogs
  150. //@line 40 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\shared\src\badCertHandler.js"
  151.  
  152. /**
  153.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  154.  */
  155. function checkCert(channel) {
  156.   if (!channel.originalURI.schemeIs("https"))  // bypass
  157.     return;
  158.  
  159.   const Ci = Components.interfaces;  
  160.   var cert =
  161.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  162.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  163.  
  164.   var issuer = cert.issuer;
  165.   while (issuer && !cert.equals(issuer)) {
  166.     cert = issuer;
  167.     issuer = cert.issuer;
  168.   }
  169.  
  170.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  171.     throw "cert issuer is not built-in";
  172. }
  173.  
  174. /**
  175.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  176.  * security dialogs from being shown to the user.  It is better to simply fail
  177.  * if the certificate is bad. See bug 304286.
  178.  */
  179. function BadCertHandler() {
  180. }
  181. BadCertHandler.prototype = {
  182.  
  183.   // nsIChannelEventSink
  184.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  185.     // make sure the certificate of the old channel checks out before we follow
  186.     // a redirect from it.  See bug 340198.
  187.     checkCert(oldChannel);
  188.   },
  189.  
  190.   // Suppress any certificate errors
  191.   notifyCertProblem: function(socketInfo, status, targetSite) {
  192.     return true;
  193.   },
  194.  
  195.   // Suppress any ssl errors
  196.   notifySSLError: function(socketInfo, error, targetSite) {
  197.     return true;
  198.   },
  199.  
  200.   // nsIInterfaceRequestor
  201.   getInterface: function(iid) {
  202.     return this.QueryInterface(iid);
  203.   },
  204.  
  205.   // nsISupports
  206.   QueryInterface: function(iid) {
  207.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  208.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  209.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  210.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  211.         !iid.equals(Components.interfaces.nsISupports))
  212.       throw Components.results.NS_ERROR_NO_INTERFACE;
  213.     return this;
  214.   }
  215. };
  216. //@line 191 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  217.  
  218. /**
  219.  * Creates a Version Checker object.
  220.  * @returns A handle to the global Version Checker service.
  221.  */
  222. function getVersionChecker() {
  223.   if (!gVersionChecker) {
  224.     gVersionChecker = Cc["@mozilla.org/xpcom/version-comparator;1"].
  225.                       getService(Ci.nsIVersionComparator);
  226.   }
  227.   return gVersionChecker;
  228. }
  229.  
  230. var BundleManager = {
  231.   /**
  232.   * Creates and returns a String Bundle at the specified URI
  233.   * @param   bundleURI
  234.   *          The URI of the bundle to load
  235.   * @returns A nsIStringBundle which was retrieved.
  236.   */
  237.   getBundle: function(bundleURI) {
  238.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  239.               getService(Ci.nsIStringBundleService);
  240.     return sbs.createBundle(bundleURI);
  241.   },
  242.  
  243.   _appName: "",
  244.  
  245.   /**
  246.    * The Application's display name.
  247.    */
  248.   get appName() {
  249.     if (!this._appName) {
  250.       var brandBundle = this.getBundle(URI_BRAND_PROPERTIES)
  251.       this._appName = brandBundle.GetStringFromName("brandShortName");
  252.     }
  253.     return this._appName;
  254.   }
  255. };
  256.  
  257. ///////////////////////////////////////////////////////////////////////////////
  258. //
  259. // Utility Functions
  260. //
  261. function EM_NS(property) {
  262.   return PREFIX_NS_EM + property;
  263. }
  264.  
  265. function CHROME_NS(property) {
  266.   return PREFIX_NS_CHROME + property;
  267. }
  268.  
  269. function EM_R(property) {
  270.   return gRDF.GetResource(EM_NS(property));
  271. }
  272.  
  273. function EM_L(literal) {
  274.   return gRDF.GetLiteral(literal);
  275. }
  276.  
  277. function EM_I(integer) {
  278.   return gRDF.GetIntLiteral(integer);
  279. }
  280.  
  281. function EM_D(integer) {
  282.   return gRDF.GetDateLiteral(integer);
  283. }
  284.  
  285. /**
  286.  * Gets a preference value, handling the case where there is no default.
  287.  * @param   func
  288.  *          The name of the preference function to call, on nsIPrefBranch
  289.  * @param   preference
  290.  *          The name of the preference
  291.  * @param   defaultValue
  292.  *          The default value to return in the event the preference has
  293.  *          no setting
  294.  * @returns The value of the preference, or undefined if there was no
  295.  *          user or default value.
  296.  */
  297. function getPref(func, preference, defaultValue) {
  298.   try {
  299.     return gPref[func](preference);
  300.   }
  301.   catch (e) {
  302.   }
  303.   return defaultValue;
  304. }
  305.  
  306. /**
  307.  * Initializes a RDF Container at a URI in a datasource.
  308.  * @param   datasource
  309.  *          The datasource the container is in
  310.  * @param   root
  311.  *          The RDF Resource which is the root of the container.
  312.  * @returns The nsIRDFContainer, initialized at the root.
  313.  */
  314. function getContainer(datasource, root) {
  315.   var ctr = Cc["@mozilla.org/rdf/container;1"].
  316.             createInstance(Ci.nsIRDFContainer);
  317.   ctr.Init(datasource, root);
  318.   return ctr;
  319. }
  320.  
  321. /**
  322.  * Gets a RDF Resource for item with the given ID
  323.  * @param   id
  324.  *          The GUID of the item to construct a RDF resource to the
  325.  *          active item for
  326.  * @returns The RDF Resource to the Active item.
  327.  */
  328. function getResourceForID(id) {
  329.   return gRDF.GetResource(PREFIX_ITEM_URI + id);
  330. }
  331.  
  332. /**
  333.  * Construct a nsIUpdateItem with the supplied metadata
  334.  * ...
  335.  */
  336. function makeItem(id, version, locationKey, minVersion, maxVersion, name,
  337.                   updateURL, updateHash, iconURL, updateRDF, updateKey, type, 
  338.                   targetAppID) {
  339.   var item = new UpdateItem();
  340.   item.init(id, version, locationKey, minVersion, maxVersion, name,
  341.             updateURL, updateHash, iconURL, updateRDF, updateKey, type,
  342.             targetAppID);
  343.   return item;
  344. }
  345.  
  346. /**
  347.  * Gets the specified directory at the specified hierarchy under a
  348.  * Directory Service key.
  349.  * @param   key
  350.  *          The Directory Service Key to start from
  351.  * @param   pathArray
  352.  *          An array of path components to locate beneath the directory
  353.  *          specified by |key|
  354.  * @return  nsIFile object for the location specified. If the directory
  355.  *          requested does not exist, it is created, along with any
  356.  *          parent directories that need to be created.
  357.  */
  358. function getDir(key, pathArray) {
  359.   return getDirInternal(key, pathArray, true);
  360. }
  361.  
  362. /**
  363.  * Gets the specified directory at the specified hierarchy under a
  364.  * Directory Service key.
  365.  * @param   key
  366.  *          The Directory Service Key to start from
  367.  * @param   pathArray
  368.  *          An array of path components to locate beneath the directory
  369.  *          specified by |key|
  370.  * @return  nsIFile object for the location specified. If the directory
  371.  *          requested does not exist, it is NOT created.
  372.  */
  373. function getDirNoCreate(key, pathArray) {
  374.   return getDirInternal(key, pathArray, false);
  375. }
  376.  
  377. /**
  378.  * Gets the specified directory at the specified hierarchy under a
  379.  * Directory Service key.
  380.  * @param   key
  381.  *          The Directory Service Key to start from
  382.  * @param   pathArray
  383.  *          An array of path components to locate beneath the directory
  384.  *          specified by |key|
  385.  * @param   shouldCreate
  386.  *          true if the directory hierarchy specified in |pathArray|
  387.  *          should be created if it does not exist,
  388.  *          false otherwise.
  389.  * @return  nsIFile object for the location specified.
  390.  */
  391. function getDirInternal(key, pathArray, shouldCreate) {
  392.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  393.                     getService(Ci.nsIProperties);
  394.   var dir = fileLocator.get(key, Ci.nsILocalFile);
  395.   for (var i = 0; i < pathArray.length; ++i) {
  396.     dir.append(pathArray[i]);
  397.     if (shouldCreate && !dir.exists())
  398.       dir.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  399.   }
  400.   dir.followLinks = false;
  401.   return dir;
  402. }
  403.  
  404. /**
  405.  * Gets the file at the specified hierarchy under a Directory Service key.
  406.  * @param   key
  407.  *          The Directory Service Key to start from
  408.  * @param   pathArray
  409.  *          An array of path components to locate beneath the directory
  410.  *          specified by |key|. The last item in this array must be the
  411.  *          leaf name of a file.
  412.  * @return  nsIFile object for the file specified. The file is NOT created
  413.  *          if it does not exist, however all required directories along
  414.  *          the way are.
  415.  */
  416. function getFile(key, pathArray) {
  417.   var file = getDir(key, pathArray.slice(0, -1));
  418.   file.append(pathArray[pathArray.length - 1]);
  419.   return file;
  420. }
  421.  
  422. /**
  423.  * Gets the descriptor of a directory as a relative path to common base
  424.  * directories (profile, user home, app install dir, etc).
  425.  *
  426.  * @param   itemLocation
  427.  *          The nsILocalFile representing the item's directory.
  428.  * @param   installLocation the nsIInstallLocation for this item
  429.  */
  430. function getDescriptorFromFile(itemLocation, installLocation) {
  431.   var baseDir = installLocation.location;
  432.  
  433.   if (baseDir && baseDir.contains(itemLocation, true)) {
  434.     return "rel%" + itemLocation.getRelativeDescriptor(baseDir);
  435.   }
  436.  
  437.   return "abs%" + itemLocation.persistentDescriptor;
  438. }
  439.  
  440. function getAbsoluteDescriptor(itemLocation) {
  441.   return itemLocation.persistentDescriptor;
  442. }
  443.  
  444. /**
  445.  * Initializes a Local File object based on a descriptor
  446.  * provided by "getDescriptorFromFile".
  447.  *
  448.  * @param   descriptor
  449.  *          The descriptor that locates the directory
  450.  * @param   installLocation
  451.  *          The nsIInstallLocation object for this item.
  452.  * @returns The nsILocalFile object representing the location of the item
  453.  */
  454. function getFileFromDescriptor(descriptor, installLocation) {
  455.   var location = Cc["@mozilla.org/file/local;1"].
  456.                  createInstance(Ci.nsILocalFile);
  457.  
  458.   var m = descriptor.match(/^(abs|rel)\%(.*)$/);
  459.   if (!m)
  460.     throw Cr.NS_ERROR_INVALID_ARG;
  461.  
  462.   if (m[1] == "rel") {
  463.     location.setRelativeDescriptor(installLocation.location, m[2]);
  464.   }
  465.   else {
  466.     location.persistentDescriptor = m[2];
  467.   }
  468.  
  469.   return location;
  470. }
  471.  
  472. /**
  473.  * Determines if a file is an item package - either a XPI or a JAR file.
  474.  * @param   file
  475.  *          The file to check
  476.  * @returns true if the file is an item package, false otherwise.
  477.  */
  478. function fileIsItemPackage(file) {
  479.   var fileURL = getURIFromFile(file);
  480.   if (fileURL instanceof Ci.nsIURL)
  481.     var extension = fileURL.fileExtension.toLowerCase();
  482.   return extension == "xpi" || extension == "jar";
  483. }
  484.  
  485. /**
  486.  * Opens a safe file output stream for writing.
  487.  * @param   file
  488.  *          The file to write to.
  489.  * @param   modeFlags
  490.  *          (optional) File open flags. Can be undefined.
  491.  * @returns nsIFileOutputStream to write to.
  492.  */
  493. function openSafeFileOutputStream(file, modeFlags) {
  494.   var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  495.             createInstance(Ci.nsIFileOutputStream);
  496.   if (modeFlags === undefined)
  497.     modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  498.   if (!file.exists())
  499.     file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  500.   fos.init(file, modeFlags, PERMS_FILE, 0);
  501.   return fos;
  502. }
  503.  
  504. /**
  505.  * Closes a safe file output stream.
  506.  * @param   stream
  507.  *          The stream to close.
  508.  */
  509. function closeSafeFileOutputStream(stream) {
  510.   if (stream instanceof Ci.nsISafeOutputStream)
  511.     stream.finish();
  512.   else
  513.     stream.close();
  514. }
  515.  
  516. /**
  517.  * Deletes a directory and its children. First it tries nsIFile::Remove(true).
  518.  * If that fails it will fall back to recursing, setting the appropriate
  519.  * permissions, and deleting the current entry. This is needed for when we have
  520.  * rights to delete a directory but there are entries that have a read-only
  521.  * attribute (e.g. a copy restore from a read-only CD, etc.)
  522.  * @param   dir
  523.  *          A nsIFile for the directory to be deleted
  524.  */
  525. function removeDirRecursive(dir) {
  526.   try {
  527.     dir.remove(true);
  528.     return;
  529.   }
  530.   catch (e) {
  531.   }
  532.  
  533.   var dirEntries = dir.directoryEntries;
  534.   while (dirEntries.hasMoreElements()) {
  535.     var entry = dirEntries.getNext().QueryInterface(Ci.nsIFile);
  536.  
  537.     if (entry.isDirectory()) {
  538.       removeDirRecursive(entry);
  539.     }
  540.     else {
  541.       entry.permissions = PERMS_FILE;
  542.       entry.remove(false);
  543.     }
  544.   }
  545.   dir.permissions = PERMS_DIRECTORY;
  546.   dir.remove(true);
  547. }
  548.  
  549. /**
  550.  * Logs a string to the error console.
  551.  * @param   string
  552.  *          The string to write to the error console.
  553.  */
  554. function LOG(string) {
  555.   if (gLoggingEnabled) {
  556.     dump("*** " + string + "\n");
  557.     if (gConsole)
  558.       gConsole.logStringMessage(string);
  559.   }
  560. }
  561.  
  562. /**
  563.  * Logs a string to the error console and to a permanent log file. 
  564.  * @param   string
  565.  *          The string to write out.
  566.  */  
  567. function ERROR(string) {
  568.   LOG(string);
  569.   try {
  570.     var tstamp = new Date();
  571.     var logfile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_LOG]);
  572.     var stream = Cc["@mozilla.org/network/file-output-stream;1"].
  573.                  createInstance(Ci.nsIFileOutputStream);
  574.     stream.init(logfile, 0x02 | 0x08 | 0x10, 0666, 0); // write, create, append
  575.     var writer = Cc["@mozilla.org/intl/converter-output-stream;1"].
  576.                  createInstance(Ci.nsIConverterOutputStream);
  577.     writer.init(stream, "UTF-8", 0, 0x0000);
  578.     string = tstamp.toLocaleFormat("%Y-%m-%d %H:%M:%S - ") + string;
  579.     writer.writeString(string + "\n");
  580.     writer.close();
  581.   }
  582.   catch (e) { }
  583. }
  584.  
  585. /**
  586.  * Randomize the specified file name. Used to force RDF to bypass the cache
  587.  * when loading certain types of files.
  588.  * @param   fileName
  589.  *          A file name to randomize, e.g. install.rdf
  590.  * @returns A randomized file name, e.g. install-xyz.rdf
  591.  */
  592. function getRandomFileName(fileName) {
  593.   var extensionDelimiter = fileName.lastIndexOf(".");
  594.   var prefix = fileName.substr(0, extensionDelimiter);
  595.   var suffix = fileName.substr(extensionDelimiter);
  596.  
  597.   var characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  598.   var nameString = prefix + "-";
  599.   for (var i = 0; i < 3; ++i) {
  600.     var index = Math.round((Math.random()) * characters.length);
  601.     nameString += characters.charAt(index);
  602.   }
  603.   return nameString + "." + suffix;
  604. }
  605.  
  606. /**
  607.  * Get the RDF URI prefix of a nsIUpdateItem type. This function should be used
  608.  * ONLY to support Firefox 1.0 Update RDF files! Item URIs in the datasource
  609.  * are NOT prefixed.
  610.  * @param   type
  611.  *          The nsIUpdateItem type to find a RDF URI prefix for
  612.  * @returns The RDF URI prefix.
  613.  */
  614. function getItemPrefix(type) {
  615.   if (type & Ci.nsIUpdateItem.TYPE_EXTENSION)
  616.     return PREFIX_EXTENSION;
  617.   else if (type & Ci.nsIUpdateItem.TYPE_THEME)
  618.     return PREFIX_THEME;
  619.   return PREFIX_ITEM_URI;
  620. }
  621.  
  622. /**
  623.  * Trims a prefix from a string.
  624.  * @param   string
  625.  *          The source string
  626.  * @param   prefix
  627.  *          The prefix to remove.
  628.  * @returns The suffix (string - prefix)
  629.  */
  630. function stripPrefix(string, prefix) {
  631.   return string.substr(prefix.length);
  632. }
  633.  
  634. /**
  635.  * Gets a File URL spec for a nsIFile
  636.  * @param   file
  637.  *          The file to get a file URL spec to
  638.  * @returns The file URL spec to the file
  639.  */
  640. function getURLSpecFromFile(file) {
  641.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  642.                getService(Ci.nsIIOService);
  643.   var fph = ioServ.getProtocolHandler("file")
  644.                   .QueryInterface(Ci.nsIFileProtocolHandler);
  645.   return fph.getURLSpecFromFile(file);
  646. }
  647.  
  648. /**
  649.  * Constructs a URI to a spec.
  650.  * @param   spec
  651.  *          The spec to construct a URI to
  652.  * @returns The nsIURI constructed.
  653.  */
  654. function newURI(spec) {
  655.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  656.                getService(Ci.nsIIOService);
  657.   return ioServ.newURI(spec, null, null);
  658. }
  659.  
  660. /**
  661.  * Constructs a File URI to a nsIFile
  662.  * @param   file
  663.  *          The file to construct a File URI to
  664.  * @returns The file URI to the file
  665.  */
  666. function getURIFromFile(file) {
  667.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  668.                getService(Ci.nsIIOService);
  669.   return ioServ.newFileURI(file);
  670. }
  671.  
  672. /**
  673.  * @returns Whether or not we are currently running in safe mode.
  674.  */
  675. function inSafeMode() {
  676.   return gApp.inSafeMode;
  677. }
  678.  
  679. /**
  680.  * Extract the string value from a RDF Literal or Resource
  681.  * @param   literalOrResource
  682.  *          RDF String Literal or Resource
  683.  * @returns String value of the literal or resource, or undefined if the object
  684.  *          supplied is not a RDF string literal or resource.
  685.  */
  686. function stringData(literalOrResource) {
  687.   if (literalOrResource instanceof Ci.nsIRDFLiteral)
  688.     return literalOrResource.Value;
  689.   if (literalOrResource instanceof Ci.nsIRDFResource)
  690.     return literalOrResource.Value;
  691.   return undefined;
  692. }
  693.  
  694. /**
  695.  * Extract the integer value of a RDF Literal
  696.  * @param   literal
  697.  *          nsIRDFInt literal
  698.  * @return  integer value of the literal
  699.  */
  700. function intData(literal) {
  701.   if (literal instanceof Ci.nsIRDFInt)
  702.     return literal.Value;
  703.   return undefined;
  704. }
  705.  
  706. /**
  707.  * Gets a property from an install manifest.
  708.  * @param   installManifest
  709.  *          An Install Manifest datasource to read from
  710.  * @param   property
  711.  *          The name of a proprety to read (sans EM_NS)
  712.  * @returns The literal value of the property, or undefined if the property has
  713.  *          no value.
  714.  */
  715. function getManifestProperty(installManifest, property) {
  716.   var target = installManifest.GetTarget(gInstallManifestRoot,
  717.                                          gRDF.GetResource(EM_NS(property)), true);
  718.   var val = stringData(target);
  719.   return val === undefined ? intData(target) : val;
  720. }
  721.  
  722. /**
  723.  * Given an Install Manifest Datasource, retrieves the type of item the manifest
  724.  * describes.
  725.  * @param   installManifest
  726.  *          The Install Manifest Datasource.
  727.  * @return  The nsIUpdateItem type of the item described by the manifest
  728.  *          returns TYPE_EXTENSION if attempts to determine the type fail.
  729.  */
  730. function getAddonTypeFromInstallManifest(installManifest) {
  731.   var target = installManifest.GetTarget(gInstallManifestRoot,
  732.                                          gRDF.GetResource(EM_NS("type")), true);
  733.   if (target) {
  734.     var type = stringData(target);
  735.     return type === undefined ? intData(target) : parseInt(type);
  736.   }
  737.  
  738.   // Firefox 1.0 and earlier did not support addon-type annotation on the
  739.   // Install Manifest, so we fall back to a theme-only property to
  740.   // differentiate.
  741.   if (getManifestProperty(installManifest, "internalName") !== undefined)
  742.     return Ci.nsIUpdateItem.TYPE_THEME;
  743.  
  744.   // If no type is provided, default to "Extension"
  745.   return Ci.nsIUpdateItem.TYPE_EXTENSION;
  746. }
  747.  
  748. /**
  749.  * Shows a message about an incompatible Extension/Theme.
  750.  * @param   installData
  751.  *          An Install Data object from |getInstallData|
  752.  */
  753. function showIncompatibleError(installData) {
  754.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  755.   var params = [extensionStrings.GetStringFromName("type-" + installData.type)];
  756.   var title = extensionStrings.formatStringFromName("incompatibleTitle",
  757.                                                     params, params.length);
  758.   params = [installData.name, installData.version, BundleManager.appName,
  759.             gApp.version];
  760.   var message = extensionStrings.formatStringFromName("incompatibleMessage",
  761.                                                       params, params.length);
  762.   var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  763.            getService(Ci.nsIPromptService);
  764.   ps.alert(null, title, message);
  765. }
  766.  
  767. /**
  768.  * Shows a message.
  769.  * @param   titleKey
  770.  *          String key of the title string in the Extensions localization file.
  771.  * @param   messageKey
  772.  *          String key of the message string in the Extensions localization file.
  773.  * @param   messageParams
  774.  *          Array of strings to be substituted into |messageKey|. Can be null.
  775.  */
  776. function showMessage(titleKey, titleParams, messageKey, messageParams) {
  777.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  778.   if (titleParams && titleParams.length > 0) {
  779.     var title = extensionStrings.formatStringFromName(titleKey, titleParams,
  780.                                                       titleParams.length);
  781.   }
  782.   else
  783.     title = extensionStrings.GetStringFromName(titleKey);
  784.  
  785.   if (messageParams && messageParams.length > 0) {
  786.     var message = extensionStrings.formatStringFromName(messageKey, messageParams,
  787.                                                         messageParams.length);
  788.   }
  789.   else
  790.     message = extensionStrings.GetStringFromName(messageKey);
  791.   var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  792.            getService(Ci.nsIPromptService);
  793.   ps.alert(null, title, message);
  794. }
  795.  
  796. /**
  797.  * Shows a dialog for blocklisted items.
  798.  * @param   items
  799.  *          An array of nsIUpdateItems.
  800.  * @param   fromInstall
  801.  *          Whether this is called from an install or from the blocklist
  802.  *          background check.
  803.  */
  804. function showBlocklistMessage(items, fromInstall) {
  805.   var win = null;
  806.   var params = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  807.                createInstance(Ci.nsIDialogParamBlock);
  808.   params.SetInt(0, (fromInstall ? 1 : 0));
  809.   params.SetInt(1, items.length);
  810.   params.SetNumberStrings(items.length * 2);
  811.   for (var i = 0; i < items.length; ++i)
  812.     params.SetString(i, items[i].name + " " + items[i].version);
  813.  
  814.   // if this was initiated from an install try to find the appropriate manager
  815.   if (fromInstall) {
  816.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  817.              getService(Ci.nsIWindowMediator);
  818.     win = wm.getMostRecentWindow("Extension:Manager");
  819.   }
  820.   var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  821.            getService(Ci.nsIWindowWatcher);
  822.   ww.openWindow(win, URI_EXTENSION_LIST_DIALOG, "",
  823.                 "chrome,centerscreen,modal,dialog,titlebar", params);
  824. }
  825.  
  826. /**
  827.  * Gets a zip reader for the file specified.
  828.  * @param   zipFile
  829.  *          A ZIP archive to open with a nsIZipReader.
  830.  * @return  A nsIZipReader for the file specified.
  831.  */
  832. function getZipReaderForFile(zipFile) {
  833.   try {
  834.     var zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
  835.                     createInstance(Ci.nsIZipReader);
  836.     zipReader.open(zipFile);
  837.   }
  838.   catch (e) {
  839.     zipReader.close();
  840.     throw e;
  841.   }
  842.   return zipReader;
  843. }
  844.  
  845. /**
  846.  * Extract a RDF file from a ZIP archive to a random location in the system
  847.  * temp directory.
  848.  * @param   zipFile
  849.  *          A ZIP archive to read from
  850.  * @param   fileName
  851.  *          The name of the file to read from the zip.
  852.  * @param   suppressErrors
  853.  *          Whether or not to report errors.
  854.  * @return  The file created in the temp directory.
  855.  */
  856. function extractRDFFileToTempDir(zipFile, fileName, suppressErrors) {
  857.   var file = getFile(KEY_TEMPDIR, [getRandomFileName(fileName)]);
  858.   try {
  859.     var zipReader = getZipReaderForFile(zipFile);
  860.     zipReader.extract(fileName, file);
  861.     zipReader.close();
  862.   }
  863.   catch (e) {
  864.     if (!suppressErrors) {
  865.       showMessage("missingFileTitle", [], "missingFileMessage",
  866.                   [BundleManager.appName, fileName]);
  867.       throw e;
  868.     }
  869.   }
  870.   return file;
  871. }
  872.  
  873. /**
  874.  * Gets an Install Manifest datasource from a file.
  875.  * @param   file
  876.  *          The nsIFile that contains the Install Manifest RDF
  877.  * @returns The Install Manifest datasource
  878.  */
  879. function getInstallManifest(file) {
  880.   var uri = getURIFromFile(file);
  881.   try {
  882.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  883.               createInstance(Ci.nsIFileInputStream);
  884.     fis.init(file, -1, -1, false);
  885.     var bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
  886.               createInstance(Ci.nsIBufferedInputStream);
  887.     bis.init(fis, 4096);
  888.     
  889.     var rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
  890.                     createInstance(Ci.nsIRDFXMLParser)
  891.     var ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
  892.              createInstance(Ci.nsIRDFDataSource);
  893.     var listener = rdfParser.parseAsync(ds, uri);
  894.     var channel = Cc["@mozilla.org/network/input-stream-channel;1"].
  895.                   createInstance(Ci.nsIInputStreamChannel);
  896.     channel.setURI(uri);
  897.     channel.contentStream = bis;
  898.     channel.QueryInterface(Ci.nsIChannel);
  899.     channel.contentType = "text/xml";
  900.   
  901.     listener.onStartRequest(channel, null);
  902.     try {
  903.       var pos = 0;
  904.       var count = bis.available();
  905.       while (count > 0) {
  906.         listener.onDataAvailable(channel, null, bis, pos, count);
  907.         pos += count;
  908.         count = bis.available();
  909.       }
  910.       listener.onStopRequest(channel, null, Components.results.NS_OK);
  911.       bis.close();
  912.       fis.close();
  913.  
  914.       var arcs = ds.ArcLabelsOut(gInstallManifestRoot);
  915.       if (arcs.hasMoreElements())
  916.         return ds;
  917.     }
  918.     catch (e) {
  919.       listener.onStopRequest(channel, null, e.result);
  920.       bis.close();
  921.       fis.close();
  922.     }
  923.   }
  924.   catch (e) { }
  925.  
  926.   var url = uri.QueryInterface(Ci.nsIURL);
  927.   showMessage("malformedTitle", [], "malformedMessage",
  928.               [BundleManager.appName, url.fileName]);
  929.   return null;
  930. }
  931.  
  932. /**
  933.  * Selects the closest matching localized resource in the given RDF resource
  934.  * @param   aDataSource The datasource to look in
  935.  * @param   aResource   The root resource containing the localized sections
  936.  * @returns The nsIRDFResource of the best em:localized section or null
  937.  *          if no valid match was found
  938.  */
  939. function findClosestLocalizedResource(aDataSource, aResource) {
  940.   var localizedProp = EM_R("localized");
  941.   var localeProp = EM_R("locale");
  942.  
  943.   // Holds the best matching localized resource
  944.   var bestmatch = null;
  945.   // The number of locale parts it matched with
  946.   var bestmatchcount = 0;
  947.   // The number of locale parts in the match
  948.   var bestpartcount = 0;
  949.  
  950.   var locales = [gLocale.toLowerCase()];
  951.   /* If the current locale is English then it will find a match if there is
  952.      a valid match for en-US so no point searching that locale too. */
  953.   if (locales[0].substring(0, 3) != "en-")
  954.     locales.push("en-us");
  955.  
  956.   for each (var locale in locales) {
  957.     var lparts = locale.split("-");
  958.     var localizations = aDataSource.GetTargets(aResource, localizedProp, true);
  959.     while (localizations.hasMoreElements()) {
  960.       var localized = localizations.getNext().QueryInterface(Ci.nsIRDFNode);
  961.       var list = aDataSource.GetTargets(localized, localeProp, true);
  962.       while (list.hasMoreElements()) {
  963.         var found = stringData(list.getNext().QueryInterface(Ci.nsIRDFNode));
  964.         if (!found)
  965.           continue;
  966.  
  967.         found = found.toLowerCase();
  968.  
  969.         // Exact match is returned immediately
  970.         if (locale == found)
  971.           return localized;
  972.   
  973.         var fparts = found.split("-");
  974.         /* If we have found a possible match and this one isn't any longer
  975.            then we dont need to check further. */
  976.         if (bestmatch && fparts.length < bestmatchcount)
  977.           continue;
  978.   
  979.         // Count the number of parts that match
  980.         var maxmatchcount = Math.min(fparts.length, lparts.length);
  981.         var matchcount = 0;
  982.         while (matchcount < maxmatchcount &&
  983.                fparts[matchcount] == lparts[matchcount])
  984.           matchcount++;
  985.   
  986.         /* If we matched more than the last best match or matched the same and
  987.            this locale is less specific than the last best match. */
  988.         if (matchcount > bestmatchcount ||
  989.            (matchcount == bestmatchcount && fparts.length < bestpartcount)) {
  990.           bestmatch = localized;
  991.           bestmatchcount = matchcount;
  992.           bestpartcount = fparts.length;
  993.         }
  994.       }
  995.     }
  996.     // If we found a valid match for this locale return it
  997.     if (bestmatch)
  998.       return bestmatch;
  999.   }
  1000.   return null;
  1001. }
  1002.     
  1003. /**
  1004.  * An enumeration of items in a JS array.
  1005.  * @constructor
  1006.  */
  1007. function ArrayEnumerator(aItems) {
  1008.   if (aItems) {
  1009.     for (var i = 0; i < aItems.length; ++i) {
  1010.       if (!aItems[i])
  1011.         aItems.splice(i--, 1);
  1012.     }
  1013.     this._contents = aItems;
  1014.   } else {
  1015.     this._contents = [];
  1016.   }
  1017. }
  1018.  
  1019. ArrayEnumerator.prototype = {
  1020.   _index: 0,
  1021.  
  1022.   hasMoreElements: function () {
  1023.     return this._index < this._contents.length;
  1024.   },
  1025.  
  1026.   getNext: function () {
  1027.     return this._contents[this._index++];
  1028.   }
  1029. };
  1030.  
  1031. /**
  1032.  * An enumeration of files in a JS array.
  1033.  * @param   files
  1034.  *          The files to enumerate
  1035.  * @constructor
  1036.  */
  1037. function FileEnumerator(files) {
  1038.   if (files) {
  1039.     for (var i = 0; i < files.length; ++i) {
  1040.       if (!files[i])
  1041.         files.splice(i--, 1);
  1042.     }
  1043.     this._contents = files;
  1044.   } else {
  1045.     this._contents = [];
  1046.   }
  1047. }
  1048.  
  1049. FileEnumerator.prototype = {
  1050.   _index: 0,
  1051.  
  1052.   /**
  1053.    * Gets the next file in the sequence.
  1054.    */
  1055.   get nextFile() {
  1056.     if (this._index < this._contents.length)
  1057.       return this._contents[this._index++];
  1058.     return null;
  1059.   },
  1060.  
  1061.   /**
  1062.    * Stop enumerating. Nothing to do here.
  1063.    */
  1064.   close: function() {
  1065.   }
  1066. };
  1067.  
  1068. /**
  1069.  * An object which identifies an Install Location for items, where the location
  1070.  * relationship is each item living in a directory named with its GUID under
  1071.  * the directory used when constructing this object.
  1072.  *
  1073.  * e.g. <location>\{GUID1}
  1074.  *      <location>\{GUID2}
  1075.  *      <location>\{GUID3}
  1076.  *      ...
  1077.  *
  1078.  * @param   name
  1079.  *          The string identifier of this Install Location.
  1080.  * @param   location
  1081.  *          The directory that contains the items.
  1082.  * @constructor
  1083.  */
  1084. function DirectoryInstallLocation(name, location, restricted, priority, independent) {
  1085.   this._name = name;
  1086.   if (location.exists()) {
  1087.     if (!location.isDirectory())
  1088.       throw new Error("location must be a directoy!");
  1089.   }
  1090.   else {
  1091.     try {
  1092.       location.create(Ci.nsILocalFile.DIRECTORY_TYPE, 0775);
  1093.     }
  1094.     catch (e) {
  1095.       ERROR("DirectoryInstallLocation: failed to create location " +
  1096.             " directory = " + location.path + ", exception = " + e + "\n");
  1097.     }
  1098.   }
  1099.  
  1100.   this._location = location;
  1101.   this._locationToIDMap = {};
  1102.   this._restricted = restricted;
  1103.   this._priority = priority;
  1104.   this._independent = independent;
  1105. }
  1106. DirectoryInstallLocation.prototype = {
  1107.   _name           : "",
  1108.   _location       : null,
  1109.   _locationToIDMap: null,
  1110.   _restricted     : false,
  1111.   _priority       : 0,
  1112.   _independent    : false,
  1113.   _canAccess      : null,
  1114.  
  1115.   /**
  1116.    * See nsIExtensionManager.idl
  1117.    */
  1118.   get name() {
  1119.     return this._name;
  1120.   },
  1121.  
  1122.   /**
  1123.    * Reads a directory linked to in a file.
  1124.    * @param   file
  1125.    *          The file containing the directory path
  1126.    * @returns A nsILocalFile object representing the linked directory.
  1127.    */
  1128.   _readDirectoryFromFile: function(file) {
  1129.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  1130.               createInstance(Ci.nsIFileInputStream);
  1131.     fis.init(file, -1, -1, false);
  1132.     var line = { value: "" };
  1133.     if (fis instanceof Ci.nsILineInputStream)
  1134.       fis.readLine(line);
  1135.     fis.close();
  1136.     if (line.value) {
  1137.       var linkedDirectory = Cc["@mozilla.org/file/local;1"].
  1138.                             createInstance(Ci.nsILocalFile);
  1139.       try {
  1140.         linkedDirectory.initWithPath(line.value);
  1141.       }
  1142.       catch (e) {
  1143.         linkedDirectory.setRelativeDescriptor(file.parent, line.value);
  1144.       }
  1145.  
  1146.       return linkedDirectory;
  1147.     }
  1148.     return null;
  1149.   },
  1150.  
  1151.   /**
  1152.    * See nsIExtensionManager.idl
  1153.    */
  1154.   get itemLocations() {
  1155.     var locations = [];
  1156.     if (!this._location.exists())
  1157.       return new FileEnumerator(locations);
  1158.  
  1159.     try {
  1160.       var entries = this._location.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1161.       while (true) {
  1162.         var entry = entries.nextFile;
  1163.         if (!entry)
  1164.           break;
  1165.         entry instanceof Ci.nsILocalFile;
  1166.         if (!entry.isDirectory() && gIDTest.test(entry.leafName)) {
  1167.           var linkedDirectory = this._readDirectoryFromFile(entry);
  1168.           if (linkedDirectory && linkedDirectory.exists() &&
  1169.               linkedDirectory.isDirectory()) {
  1170.             locations.push(linkedDirectory);
  1171.             this._locationToIDMap[linkedDirectory.persistentDescriptor] = entry.leafName;
  1172.           }
  1173.         }
  1174.         else
  1175.           locations.push(entry);
  1176.       }
  1177.       entries.close();
  1178.     }
  1179.     catch (e) {
  1180.     }
  1181.     return new FileEnumerator(locations);
  1182.   },
  1183.  
  1184.   /**
  1185.    * Retrieves the GUID for an item at the specified location.
  1186.    * @param   file
  1187.    *          The location where an item might live.
  1188.    * @returns The ID for an item that might live at the location specified.
  1189.    *
  1190.    * N.B. This function makes no promises about whether or not this path is
  1191.    *      actually maintained by this Install Location.
  1192.    */
  1193.   getIDForLocation: function(file) {
  1194.     var section = file.leafName;
  1195.     var filePD = file.persistentDescriptor;
  1196.     if (filePD in this._locationToIDMap)
  1197.       section = this._locationToIDMap[filePD];
  1198.  
  1199.     if (gIDTest.test(section))
  1200.       return RegExp.$1;
  1201.     return undefined;
  1202.   },
  1203.  
  1204.   /**
  1205.    * See nsIExtensionManager.idl
  1206.    */
  1207.   get location() {
  1208.     return this._location.clone();
  1209.   },
  1210.  
  1211.   /**
  1212.    * See nsIExtensionManager.idl
  1213.    */
  1214.   get restricted() {
  1215.     return this._restricted;
  1216.   },
  1217.  
  1218.   /**
  1219.    * See nsIExtensionManager.idl
  1220.    */
  1221.   get canAccess() {
  1222.     if (this._canAccess != null)
  1223.       return this._canAccess;
  1224.  
  1225.     var testFile = this.location;
  1226.     testFile.append("Access Privileges Test");
  1227.     try {
  1228.       testFile.createUnique(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1229.       testFile.remove(false);
  1230.       this._canAccess = true;
  1231.     }
  1232.     catch (e) {
  1233.       this._canAccess = false;
  1234.     }
  1235.     return this._canAccess;
  1236.   },
  1237.  
  1238.   /**
  1239.    * See nsIExtensionManager.idl
  1240.    */
  1241.   get priority() {
  1242.     return this._priority;
  1243.   },
  1244.  
  1245.   /**
  1246.    * See nsIExtensionManager.idl
  1247.    */
  1248.   getItemLocation: function(id) {
  1249.     var itemLocation = this.location;
  1250.     itemLocation.append(id);
  1251.     if (itemLocation.exists() && !itemLocation.isDirectory())
  1252.       return this._readDirectoryFromFile(itemLocation);
  1253.     if (!itemLocation.exists() && this.canAccess)
  1254.       itemLocation.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1255.     return itemLocation;
  1256.   },
  1257.  
  1258.   /**
  1259.    * See nsIExtensionManager.idl
  1260.    */
  1261.   itemIsManagedIndependently: function(id) {
  1262.     if (this._independent)
  1263.       return true;
  1264.     var itemLocation = this.location;
  1265.     itemLocation.append(id);
  1266.     return itemLocation.exists() && !itemLocation.isDirectory();
  1267.   },
  1268.  
  1269.   /**
  1270.    * See nsIExtensionManager.idl
  1271.    */
  1272.   getItemFile: function(id, filePath) {
  1273.     var itemLocation = this.getItemLocation(id).clone();
  1274.     var parts = filePath.split("/");
  1275.     for (var i = 0; i < parts.length; ++i)
  1276.       itemLocation.append(parts[i]);
  1277.     return itemLocation;
  1278.   },
  1279.  
  1280.   /**
  1281.    * Stages the specified file for later.
  1282.    * @param   file
  1283.    *          The file to stage
  1284.    * @param   id
  1285.    *          The GUID of the item the file represents
  1286.    */
  1287.   stageFile: function(file, id) {
  1288.     var stagedFile = this.location;
  1289.     stagedFile.append(DIR_STAGE);
  1290.     stagedFile.append(id);
  1291.     stagedFile.append(file.leafName);
  1292.  
  1293.     // When an incompatible update is successful the file is already staged
  1294.     if (stagedFile.equals(file))
  1295.       return stagedFile;
  1296.  
  1297.     if (stagedFile.exists())
  1298.       stagedFile.remove(false);
  1299.  
  1300.     file.copyTo(stagedFile.parent, stagedFile.leafName);
  1301.  
  1302.     // If the file has incorrect permissions set, correct them now.
  1303.     if (!stagedFile.isWritable())
  1304.       stagedFile.permissions = PERMS_FILE;
  1305.  
  1306.     return stagedFile;
  1307.   },
  1308.  
  1309.   /**
  1310.    * Returns the most recently staged package (e.g. the last XPI or JAR in a
  1311.    * directory) for an item and removes items that do not qualify.
  1312.    * @param   id
  1313.    *          The ID of the staged package
  1314.    * @returns an nsIFile if the package exists otherwise null.
  1315.    */
  1316.   getStageFile: function(id) {
  1317.     var stageFile = null;
  1318.     var stageDir = this.location;
  1319.     stageDir.append(DIR_STAGE);
  1320.     stageDir.append(id);
  1321.     if (!stageDir.exists() || !stageDir.isDirectory())
  1322.       return null;
  1323.     try {
  1324.       var entries = stageDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1325.       while (entries.hasMoreElements()) {
  1326.         var file = entries.nextFile;
  1327.         if (!(file instanceof Ci.nsILocalFile))
  1328.           continue;
  1329.         if (file.isDirectory())
  1330.           removeDirRecursive(file);
  1331.         else if (fileIsItemPackage(file)) {
  1332.           if (stageFile)
  1333.             stageFile.remove(false);
  1334.           stageFile = file;
  1335.         }
  1336.         else
  1337.           file.remove(false);
  1338.       }
  1339.     }
  1340.     catch (e) {
  1341.     }
  1342.     if (entries instanceof Ci.nsIDirectoryEnumerator)
  1343.       entries.close();
  1344.     return stageFile;
  1345.   },
  1346.  
  1347.   /**
  1348.    * Removes a file from the stage. This cleans up the stage if there is nothing
  1349.    * else left after the remove operation.
  1350.    * @param   file
  1351.    *          The file to remove.
  1352.    */
  1353.   removeFile: function(file) {
  1354.     if (file.exists())
  1355.       file.remove(false);
  1356.     var parent = file.parent;
  1357.     var entries = parent.directoryEntries;
  1358.     try {
  1359.       // XXXrstrong calling hasMoreElements on a nsIDirectoryEnumerator after
  1360.       // it has been removed will cause a crash on Mac OS X - bug 292823
  1361.       while (parent && !parent.equals(this.location) &&
  1362.             !entries.hasMoreElements()) {
  1363.         parent.remove(false);
  1364.         parent = parent.parent;
  1365.         entries = parent.directoryEntries;
  1366.       }
  1367.       if (entries instanceof Ci.nsIDirectoryEnumerator)
  1368.         entries.close();
  1369.     }
  1370.     catch (e) {
  1371.       ERROR("DirectoryInstallLocation::removeFile: failed to remove staged " +
  1372.             " directory = " + parent.path + ", exception = " + e + "\n");
  1373.     }
  1374.   },
  1375.  
  1376.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIInstallLocation])
  1377. };
  1378.  
  1379. //@line 1354 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  1380.  
  1381. const nsIWindowsRegKey = Ci.nsIWindowsRegKey;
  1382.  
  1383. /**
  1384.  * An object that identifies the location of installed items based on entries
  1385.  * in the Windows registry.  For each application a subkey is defined that
  1386.  * contains a set of values, where the name of each value is a GUID and the
  1387.  * contents of the value is a filesystem path identifying a directory
  1388.  * containing an installed item.
  1389.  *
  1390.  * @param   name
  1391.  *          The string identifier of this Install Location.
  1392.  * @param   rootKey
  1393.  *          The root key (one of the ROOT_KEY_ values from nsIWindowsRegKey).
  1394.  * @param   restricted
  1395.  *          Indicates that the location may be restricted (e.g., this is
  1396.  *          usually true of a system level install location).
  1397.  * @param   priority
  1398.  *          The priority of this install location.
  1399.  * @constructor
  1400.  */
  1401. function WinRegInstallLocation(name, rootKey, restricted, priority) {
  1402.   this._name = name;
  1403.   this._rootKey = rootKey;
  1404.   this._restricted = restricted;
  1405.   this._priority = priority;
  1406.   this._IDToDirMap = {};
  1407.   this._DirToIDMap = {};
  1408.  
  1409.   // Reading the registry may throw an exception, and that's ok.  In error
  1410.   // cases, we just leave ourselves in the empty state.
  1411.   try {
  1412.     var path = this._appKeyPath + "\\Extensions";
  1413.     var key = Cc["@mozilla.org/windows-registry-key;1"].
  1414.               createInstance(nsIWindowsRegKey);
  1415.     key.open(this._rootKey, path, nsIWindowsRegKey.ACCESS_READ);
  1416.     this._readAddons(key);
  1417.   } catch (e) {
  1418.     if (key)
  1419.       key.close();
  1420.   }
  1421. }
  1422. WinRegInstallLocation.prototype = {
  1423.   _name       : "",
  1424.   _rootKey    : null,
  1425.   _restricted : false,
  1426.   _priority   : 0,
  1427.   _IDToDirMap : null,  // mapping from ID to directory object
  1428.   _DirToIDMap : null,  // mapping from directory path to ID
  1429.  
  1430.   /**
  1431.    * Retrieves the path of this Application's data key in the registry.
  1432.    */
  1433.   get _appKeyPath() {
  1434.     var appVendor = gApp.vendor;
  1435.     var appName = gApp.name;
  1436.  
  1437. //@line 1416 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  1438.  
  1439.     // XULRunner-based apps may intentionally not specify a vendor:
  1440.     if (appVendor != "")
  1441.       appVendor += "\\";
  1442.  
  1443.     return "SOFTWARE\\" + appVendor + appName;
  1444.   },
  1445.  
  1446.   /**
  1447.    * Read the registry and build a mapping between GUID and directory for each
  1448.    * installed item.
  1449.    * @param   key
  1450.    *          The key that contains the GUID->path pairs
  1451.    */
  1452.   _readAddons: function(key) {
  1453.     var count = key.valueCount;
  1454.     for (var i = 0; i < count; ++i) {
  1455.       var id = key.getValueName(i);
  1456.  
  1457.       var dir = Cc["@mozilla.org/file/local;1"].
  1458.                 createInstance(Ci.nsILocalFile);
  1459.       dir.initWithPath(key.readStringValue(id));
  1460.  
  1461.       if (dir.exists() && dir.isDirectory()) {
  1462.         this._IDToDirMap[id] = dir;
  1463.         this._DirToIDMap[dir.path] = id;
  1464.       }
  1465.     }
  1466.   },
  1467.  
  1468.   get name() {
  1469.     return this._name;
  1470.   },
  1471.  
  1472.   get itemLocations() {
  1473.     var locations = [];
  1474.     for (var id in this._IDToDirMap) {
  1475.       locations.push(this._IDToDirMap[id]);
  1476.     }
  1477.     return new FileEnumerator(locations);
  1478.   },
  1479.  
  1480.   get location() {
  1481.     return null;
  1482.   },
  1483.  
  1484.   get restricted() {
  1485.     return this._restricted;
  1486.   },
  1487.  
  1488.   // you should never be able to write to this location
  1489.   get canAccess() {
  1490.     return false;
  1491.   },
  1492.  
  1493.   get priority() {
  1494.     return this._priority;
  1495.   },
  1496.  
  1497.   getItemLocation: function(id) {
  1498.     return this._IDToDirMap[id];
  1499.   },
  1500.  
  1501.   getIDForLocation: function(dir) {
  1502.     return this._DirToIDMap[dir.path];
  1503.   },
  1504.  
  1505.   getItemFile: function(id, filePath) {
  1506.     var itemLocation = this.getItemLocation(id).clone();
  1507.     var parts = filePath.split("/");
  1508.     for (var i = 0; i < parts.length; ++i)
  1509.       itemLocation.append(parts[i]);
  1510.     return itemLocation;
  1511.   },
  1512.  
  1513.   itemIsManagedIndependently: function(id) {
  1514.     return true;
  1515.   },
  1516.  
  1517.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIInstallLocation])
  1518. };
  1519.  
  1520. //@line 1499 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  1521.  
  1522. /**
  1523.  * An object which handles the installation of an Extension.
  1524.  * @constructor
  1525.  */
  1526. function Installer(ds, id, installLocation, type) {
  1527.   this._ds = ds;
  1528.   this._id = id;
  1529.   this._type = type;
  1530.   this._installLocation = installLocation;
  1531. }
  1532. Installer.prototype = {
  1533.   // Item metadata
  1534.   _id: null,
  1535.   _ds: null,
  1536.   _installLocation: null,
  1537.   _metadataDS: null,
  1538.  
  1539.   /**
  1540.    * Gets the Install Manifest datasource we are installing from.
  1541.    */
  1542.   get metadataDS() {
  1543.     if (!this._metadataDS) {
  1544.       var metadataFile = this._installLocation
  1545.                              .getItemFile(this._id, FILE_INSTALL_MANIFEST);
  1546.       if (!metadataFile.exists())
  1547.         return null;
  1548.       this._metadataDS = getInstallManifest(metadataFile);
  1549.       if (!this._metadataDS) {
  1550.         LOG("Installer::install: metadata datasource for extension " +
  1551.             this._id + " at " + metadataFile.path + " could not be loaded. " +
  1552.             " Installation will not proceed.");
  1553.       }
  1554.     }
  1555.     return this._metadataDS;
  1556.   },
  1557.  
  1558.   /**
  1559.    * Installs the Extension
  1560.    * @param   file
  1561.    *          A XPI/JAR file to install from. If this is null or does not exist,
  1562.    *          the item is assumed to be an expanded directory, located at the GUID
  1563.    *          key in the supplied Install Location.
  1564.    */
  1565.   installFromFile: function(file) {
  1566.     // Move files from the staging dir into the extension's final home.
  1567.     if (file && file.exists()) {
  1568.       this._installExtensionFiles(file);
  1569.     }
  1570.  
  1571.     if (!this.metadataDS)
  1572.       return;
  1573.  
  1574.     // Upgrade old-style contents.rdf Chrome Manifests if necessary.
  1575.     if (this._type == Ci.nsIUpdateItem.TYPE_THEME)
  1576.       this.upgradeThemeChrome();
  1577.     else
  1578.       this.upgradeExtensionChrome();
  1579.  
  1580.     // Add metadata for the extension to the global extension metadata set
  1581.     this._ds.addItemMetadata(this._id, this.metadataDS, this._installLocation);
  1582.   },
  1583.  
  1584.   /**
  1585.    * Safely extract the Extension's files into the target folder.
  1586.    * @param   file
  1587.    *          The XPI/JAR file to install from.
  1588.    */
  1589.   _installExtensionFiles: function(file) {
  1590.     /**
  1591.       * Callback for |safeInstallOperation| that performs file level installation
  1592.       * steps for an Extension.
  1593.       * @param   extensionID
  1594.       *          The GUID of the Extension being installed.
  1595.       * @param   installLocation
  1596.       *          The Install Location where the Extension is being installed.
  1597.       * @param   xpiFile
  1598.       *          The source XPI file that contains the Extension.
  1599.       */
  1600.     function extractExtensionFiles(extensionID, installLocation, xpiFile) {
  1601.       // Create a logger to log install operations for uninstall. This must be
  1602.       // created in the |safeInstallOperation| callback, since it creates a file
  1603.       // in the target directory. If we do this outside of the callback, we may
  1604.       // be clobbering a file we should not be.
  1605.       var zipReader = getZipReaderForFile(xpiFile);
  1606.  
  1607.       // create directories first
  1608.       var entries = zipReader.findEntries("*/");
  1609.       while (entries.hasMore()) {
  1610.         var entryName = entries.getNext();
  1611.         var target = installLocation.getItemFile(extensionID, entryName);
  1612.         if (!target.exists()) {
  1613.           try {
  1614.             target.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1615.           }
  1616.           catch (e) {
  1617.             ERROR("extractExtensionsFiles: failed to create target directory for extraction " +
  1618.                   " file = " + target.path + ", exception = " + e + "\n");
  1619.           }
  1620.         }
  1621.       }
  1622.  
  1623.       entries = zipReader.findEntries(null);
  1624.       while (entries.hasMore()) {
  1625.         var entryName = entries.getNext();
  1626.         target = installLocation.getItemFile(extensionID, entryName);
  1627.         if (target.exists())
  1628.           continue;
  1629.  
  1630.         try {
  1631.           target.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1632.         }
  1633.         catch (e) {
  1634.           ERROR("extractExtensionsFiles: failed to create target file for extraction " +
  1635.                 " file = " + target.path + ", exception = " + e + "\n");
  1636.         }
  1637.         zipReader.extract(entryName, target);
  1638.       }
  1639.       zipReader.close();
  1640.     }
  1641.  
  1642.     /**
  1643.       * Callback for |safeInstallOperation| that performs file level installation
  1644.       * steps for a Theme.
  1645.       * @param   id
  1646.       *          The GUID of the Theme being installed.
  1647.       * @param   installLocation
  1648.       *          The Install Location where the Theme is being installed.
  1649.       * @param   jarFile
  1650.       *          The source JAR file that contains the Theme.
  1651.       */
  1652.     function extractThemeFiles(id, installLocation, jarFile) {
  1653.       var themeDirectory = installLocation.getItemLocation(id);
  1654.       var zipReader = getZipReaderForFile(jarFile);
  1655.  
  1656.       // The only critical file is the install.rdf and we would not have
  1657.       // gotten this far without one.
  1658.       var rootFiles = [FILE_INSTALL_MANIFEST, FILE_CHROME_MANIFEST,
  1659.                        "preview.png", "icon.png"];
  1660.       for (var i = 0; i < rootFiles.length; ++i) {
  1661.         try {
  1662.           var target = installLocation.getItemFile(id, rootFiles[i]);
  1663.           zipReader.extract(rootFiles[i], target);
  1664.         }
  1665.         catch (e) {
  1666.         }
  1667.       }
  1668.  
  1669.       var manifestFile = installLocation.getItemFile(id, FILE_CHROME_MANIFEST);
  1670.       // new theme structure requires a chrome.manifest file
  1671.       if (manifestFile.exists()) {
  1672.         var entries = zipReader.findEntries(DIR_CHROME + "/*");
  1673.         while (entries.hasMore()) {
  1674.           var entryName = entries.getNext();
  1675.           if (entryName.charAt(entryName.length - 1) == "/")
  1676.             continue;
  1677.           target = installLocation.getItemFile(id, entryName);
  1678.           try {
  1679.             target.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1680.           }
  1681.           catch (e) {
  1682.             ERROR("extractThemeFiles: failed to create target file for extraction " +
  1683.                   " file = " + target.path + ", exception = " + e + "\n");
  1684.           }
  1685.           zipReader.extract(entryName, target);
  1686.         }
  1687.         zipReader.close();
  1688.       }
  1689.       else { // old theme structure requires only an install.rdf
  1690.         try {
  1691.           var contentsManifestFile = installLocation.getItemFile(id, FILE_CONTENTS_MANIFEST);
  1692.           contentsManifestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1693.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  1694.         }
  1695.         catch (e) {
  1696.           zipReader.close();
  1697.           ERROR("extractThemeFiles: failed to extract contents.rdf: " + target.path);
  1698.           throw e; // let the safe-op clean up
  1699.         }
  1700.         zipReader.close();
  1701.         var chromeDir = installLocation.getItemFile(id, DIR_CHROME);
  1702.         try {
  1703.           jarFile.copyTo(chromeDir, jarFile.leafName);
  1704.         }
  1705.         catch (e) {
  1706.           ERROR("extractThemeFiles: failed to copy theme JAR file to: " + chromeDir.path);
  1707.           throw e; // let the safe-op clean up
  1708.         }
  1709.  
  1710.         if (!installer.metadataDS && installer._type == Ci.nsIUpdateItem.TYPE_THEME) {
  1711.           var themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  1712.           if (contentsManifestFile && contentsManifestFile.exists()) {
  1713.             var contentsManifest = gRDF.GetDataSourceBlocking(getURLSpecFromFile(contentsManifestFile));
  1714.             try {
  1715.               var ctr = getContainer(contentsManifest,
  1716.                                      gRDF.GetResource("urn:mozilla:skin:root"));
  1717.               var elts = ctr.GetElements();
  1718.               var nameArc = gRDF.GetResource(CHROME_NS("displayName"));
  1719.               while (elts.hasMoreElements()) {
  1720.                 var elt = elts.getNext().QueryInterface(Ci.nsIRDFResource);
  1721.                 themeName = stringData(contentsManifest.GetTarget(elt, nameArc, true));
  1722.                 if (themeName)
  1723.                   break;
  1724.               }
  1725.             }
  1726.             catch (e) {
  1727.               themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  1728.             }
  1729.           }
  1730.           showIncompatibleError({ name: themeName, version: "",
  1731.                                   type: Ci.nsIUpdateItem.TYPE_THEME });
  1732.           LOG("Theme JAR file: " + jarFile.leafName + " contains an Old-Style " +
  1733.               "Theme that is not compatible with this version of the software.");
  1734.           throw new Error("Old Theme"); // let the safe-op clean up
  1735.         }
  1736.       }
  1737.     }
  1738.  
  1739.     var installer = this;
  1740.     var callback = extractExtensionFiles;
  1741.     if (this._type == Ci.nsIUpdateItem.TYPE_THEME)
  1742.       callback = extractThemeFiles;
  1743.     safeInstallOperation(this._id, this._installLocation,
  1744.                           { callback: callback, data: file });
  1745.   },
  1746.  
  1747.   /**
  1748.    * Upgrade contents.rdf Chrome Manifests used by this Theme to the new
  1749.    * chrome.manifest format if necessary.
  1750.    */
  1751.   upgradeThemeChrome: function() {
  1752.     // Use the Chrome Registry API to install the theme there
  1753.     var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  1754.              getService(Ci.nsIToolkitChromeRegistry);
  1755.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1756.     if (manifestFile.exists() ||
  1757.         this._id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  1758.       return;
  1759.  
  1760.     try {
  1761.       // creates a chrome manifest for themes
  1762.       var manifestURI = getURIFromFile(manifestFile);
  1763.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1764.       // We're relying on the fact that there is only one JAR file
  1765.       // in the "chrome" directory. This is a hack, but it works.
  1766.       var entries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1767.       var jarFile = entries.nextFile;
  1768.       if (jarFile) {
  1769.         var jarFileURI = getURIFromFile(jarFile);
  1770.         var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  1771.         var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1772.         var contentsFileURI = getURIFromFile(contentsFile.parent);
  1773.  
  1774.         cr.processContentsManifest(contentsFileURI, manifestURI, contentsURI, false, true);
  1775.       }
  1776.       entries.close();
  1777.       contentsFile.remove(false);
  1778.     }
  1779.     catch (e) {
  1780.       // Failed to register chrome, for any number of reasons - non-existent
  1781.       // contents.rdf file at the location specified, malformed contents.rdf,
  1782.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the
  1783.       // extension is uninstalled properly during the subsequent uninstall
  1784.       // pass in |ExtensionManager::_finishOperations|
  1785.       ERROR("upgradeThemeChrome: failed for theme " + this._id + " - why " +
  1786.             "not convert to the new chrome.manifest format while you're at it? " +
  1787.             "Failure exception: " + e);
  1788.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1789.                   [BundleManager.appName]);
  1790.  
  1791.       var stageFile = this._installLocation.getStageFile(this._id);
  1792.       if (stageFile)
  1793.         this._installLocation.removeFile(stageFile);
  1794.  
  1795.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1796.       StartupCache.write();
  1797.     }
  1798.   },
  1799.  
  1800.   /**
  1801.    * Upgrade contents.rdf Chrome Manifests used by this Extension to the new
  1802.    * chrome.manifest format if necessary.
  1803.    */
  1804.   upgradeExtensionChrome: function() {
  1805.     // If the extension is aware of the new flat chrome manifests and has
  1806.     // included one, just use it instead of generating one from the
  1807.     // install.rdf/contents.rdf data.
  1808.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1809.     if (manifestFile.exists())
  1810.       return;
  1811.  
  1812.     try {
  1813.       // Enumerate the metadata datasource files collection and register chrome
  1814.       // for each file, calling _registerChrome for each.
  1815.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1816.  
  1817.       if (!manifestFile.parent.exists())
  1818.         return;
  1819.  
  1820.       // Even if an extension doesn't have any chrome, we generate an empty
  1821.       // manifest file so that we don't try to upgrade from the "old-style"
  1822.       // chrome manifests at every startup.
  1823.       manifestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1824.  
  1825.       var manifestURI = getURIFromFile(manifestFile);
  1826.       var files = this.metadataDS.GetTargets(gInstallManifestRoot, EM_R("file"), true);
  1827.       while (files.hasMoreElements()) {
  1828.         var file = files.getNext().QueryInterface(Ci.nsIRDFResource);
  1829.         var chromeFile = chromeDir.clone();
  1830.         var fileName = file.Value.substr("urn:mozilla:extension:file:".length, file.Value.length);
  1831.         chromeFile.append(fileName);
  1832.  
  1833.         var fileURLSpec = getURLSpecFromFile(chromeFile);
  1834.         if (!chromeFile.isDirectory()) {
  1835.           var zipReader = getZipReaderForFile(chromeFile);
  1836.           fileURLSpec = "jar:" + fileURLSpec + "!/";
  1837.           var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1838.           contentsFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1839.         }
  1840.  
  1841.         var providers = [EM_R("package"), EM_R("skin"), EM_R("locale")];
  1842.         for (var i = 0; i < providers.length; ++i) {
  1843.           var items = this.metadataDS.GetTargets(file, providers[i], true);
  1844.           while (items.hasMoreElements()) {
  1845.             var item = items.getNext().QueryInterface(Ci.nsIRDFLiteral);
  1846.             var fileURI = newURI(fileURLSpec + item.Value);
  1847.             // Extract the contents.rdf files instead of opening them inside of
  1848.             // the jar. This prevents the jar from being cached by the zip
  1849.             // reader which will keep the jar in use and prevent deletion.
  1850.             if (zipReader) {
  1851.               zipReader.extract(item.Value + FILE_CONTENTS_MANIFEST, contentsFile);
  1852.               var contentsFileURI = getURIFromFile(contentsFile.parent);
  1853.             }
  1854.             else
  1855.               contentsFileURI = fileURI;
  1856.  
  1857.             var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  1858.                      getService(Ci.nsIToolkitChromeRegistry);
  1859.             cr.processContentsManifest(contentsFileURI, manifestURI, fileURI, true, false);
  1860.           }
  1861.         }
  1862.         if (zipReader) {
  1863.           zipReader.close();
  1864.           zipReader = null;
  1865.           contentsFile.remove(false);
  1866.         }
  1867.       }
  1868.     }
  1869.     catch (e) {
  1870.       // Failed to register chrome, for any number of reasons - non-existent
  1871.       // contents.rdf file at the location specified, malformed contents.rdf,
  1872.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the
  1873.       // extension is uninstalled properly during the subsequent uninstall
  1874.       // pass in |ExtensionManager::_finishOperations|
  1875.       ERROR("upgradeExtensionChrome: failed for extension " + this._id + " - why " +
  1876.             "not convert to the new chrome.manifest format while you're at it? " +
  1877.             "Failure exception: " + e);
  1878.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1879.                   [BundleManager.appName]);
  1880.  
  1881.       var stageFile = this._installLocation.getStageFile(this._id);
  1882.       if (stageFile)
  1883.         this._installLocation.removeFile(stageFile);
  1884.  
  1885.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1886.       StartupCache.write();
  1887.     }
  1888.   }
  1889. };
  1890.  
  1891. /**
  1892.  * Safely attempt to perform a caller-defined install operation for a given
  1893.  * item ID. Using aggressive success-safety checks, this function will attempt
  1894.  * to move an existing location for an item aside and then allow installation
  1895.  * into the appropriate folder. If any operation fails the installation will
  1896.  * abort and roll back from the moved-aside old version.
  1897.  * @param   itemID
  1898.  *          The GUID of the item to perform the operation on.
  1899.  * @param   installLocation
  1900.  *          The Install Location where the item is installed.
  1901.  * @param   installCallback
  1902.  *          A caller supplied JS object with the following properties:
  1903.  *          "data"      A data parameter to be passed to the callback.
  1904.  *          "callback"  A function to perform the install operation. This
  1905.  *                      function is passed three parameters:
  1906.  *                      1. The GUID of the item being operated on.
  1907.  *                      2. The Install Location where the item is installed.
  1908.  *                      3. The "data" parameter on the installCallback object.
  1909.  */
  1910. function safeInstallOperation(itemID, installLocation, installCallback) {
  1911.   var movedFiles = [];
  1912.  
  1913.   /**
  1914.    * Reverts a deep move by moving backed up files back to their original
  1915.    * location.
  1916.    */
  1917.   function rollbackMove()
  1918.   {
  1919.     for (var i = 0; i < movedFiles.length; ++i) {
  1920.       var oldFile = movedFiles[i].oldFile;
  1921.       var newFile = movedFiles[i].newFile;
  1922.       try {
  1923.         newFile.moveTo(oldFile.parent, newFile.leafName);
  1924.       }
  1925.       catch (e) {
  1926.         ERROR("safeInstallOperation: failed to roll back files after an install " +
  1927.               "operation failed. Failed to roll back: " + newFile.path + " to: " +
  1928.               oldFile.path + " ... aborting installation.");
  1929.         throw e;
  1930.       }
  1931.     }
  1932.   }
  1933.  
  1934.   /**
  1935.    * Moves a file to a new folder.
  1936.    * @param   file
  1937.    *          The file to move
  1938.    * @param   destination
  1939.    *          The target folder
  1940.    */
  1941.   function moveFile(file, destination) {
  1942.     try {
  1943.       var oldFile = file.clone();
  1944.       file.moveTo(destination, file.leafName);
  1945.       movedFiles.push({ oldFile: oldFile, newFile: file });
  1946.     }
  1947.     catch (e) {
  1948.       ERROR("safeInstallOperation: failed to back up file: " + file.path + " to: " +
  1949.             destination.path + " ... rolling back file moves and aborting " +
  1950.             "installation.");
  1951.       rollbackMove();
  1952.       throw e;
  1953.     }
  1954.   }
  1955.  
  1956.   /**
  1957.    * Moves a directory to a new location. If any part of the move fails,
  1958.    * files already moved will be rolled back.
  1959.    * @param   sourceDir
  1960.    *          The directory to move
  1961.    * @param   targetDir
  1962.    *          The destination directory
  1963.    * @param   currentDir
  1964.    *          The current directory (a subdirectory of |sourceDir| or
  1965.    *          |sourceDir| itself) we are moving files from.
  1966.    */
  1967.   function moveDirectory(sourceDir, targetDir, currentDir) {
  1968.     var entries = currentDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1969.     while (true) {
  1970.       var entry = entries.nextFile;
  1971.       if (!entry)
  1972.         break;
  1973.       if (entry.isDirectory())
  1974.         moveDirectory(sourceDir, targetDir, entry);
  1975.       else if (entry instanceof Ci.nsILocalFile) {
  1976.         var rd = entry.getRelativeDescriptor(sourceDir);
  1977.         var destination = targetDir.clone().QueryInterface(Ci.nsILocalFile);
  1978.         destination.setRelativeDescriptor(targetDir, rd);
  1979.         moveFile(entry, destination.parent);
  1980.       }
  1981.     }
  1982.     entries.close();
  1983.   }
  1984.  
  1985.   /**
  1986.    * Removes the temporary backup directory where we stored files.
  1987.    * @param   directory
  1988.    *          The backup directory to remove
  1989.    */
  1990.   function cleanUpTrash(directory) {
  1991.     try {
  1992.       // Us-generated. Safe.
  1993.       if (directory && directory.exists())
  1994.         removeDirRecursive(directory);
  1995.     }
  1996.     catch (e) {
  1997.       ERROR("safeInstallOperation: failed to clean up the temporary backup of the " +
  1998.             "older version: " + itemLocationTrash.path);
  1999.       // This is a non-fatal error. Annoying, but non-fatal.
  2000.     }
  2001.   }
  2002.  
  2003.   if (!installLocation.itemIsManagedIndependently(itemID)) {
  2004.     var itemLocation = installLocation.getItemLocation(itemID);
  2005.     if (itemLocation.exists()) {
  2006.       var trashDirName = itemID + "-trash";
  2007.       var itemLocationTrash = itemLocation.parent.clone();
  2008.       itemLocationTrash.append(trashDirName);
  2009.       if (itemLocationTrash.exists()) {
  2010.         // We can remove recursively here since this is a folder we created, not
  2011.         // one the user specified. If this fails, it'll throw, and the caller
  2012.         // should stop installation.
  2013.         try {
  2014.           removeDirRecursive(itemLocationTrash);
  2015.         }
  2016.         catch (e) {
  2017.           ERROR("safeFileOperation: failed to remove existing trash directory " +
  2018.                 itemLocationTrash.path + " ... aborting installation.");
  2019.           throw e;
  2020.         }
  2021.       }
  2022.  
  2023.       // Move the directory that contains the existing version of the item aside,
  2024.       // into {GUID}-trash. This will throw if there's a failure and the install
  2025.       // will abort.
  2026.       moveDirectory(itemLocation, itemLocationTrash, itemLocation);
  2027.  
  2028.       // Clean up the original location, if necessary. Again, this is a path we
  2029.       // generated, so it is safe to recursively delete.
  2030.       try {
  2031.         removeDirRecursive(itemLocation);
  2032.       }
  2033.       catch (e) {
  2034.         ERROR("safeInstallOperation: failed to clean up item location after its contents " +
  2035.               "were properly backed up. Failed to clean up: " + itemLocation.path +
  2036.               " ... rolling back file moves and aborting installation.");
  2037.         rollbackMove();
  2038.         cleanUpTrash(itemLocationTrash);
  2039.         throw e;
  2040.       }
  2041.     }
  2042.   }
  2043.   else if (installLocation.name == KEY_APP_PROFILE ||
  2044.            installLocation.name == KEY_APP_GLOBAL ||
  2045.            installLocation.name == KEY_APP_SYSTEM_USER) {
  2046.     // Check for a pointer file and move it aside if it exists
  2047.     var pointerFile = installLocation.location.clone();
  2048.     pointerFile.append(itemID);
  2049.     if (pointerFile.exists() && !pointerFile.isDirectory()) {
  2050.       var trashFileName = itemID + "-trash";
  2051.       var itemLocationTrash = installLocation.location.clone();
  2052.       itemLocationTrash.append(trashFileName);
  2053.       if (itemLocationTrash.exists()) {
  2054.         // We can remove recursively here since this is a folder we created, not
  2055.         // one the user specified. If this fails, it'll throw, and the caller
  2056.         // should stop installation.
  2057.         try {
  2058.           removeDirRecursive(itemLocationTrash);
  2059.         }
  2060.         catch (e) {
  2061.           ERROR("safeFileOperation: failed to remove existing trash directory " +
  2062.                 itemLocationTrash.path + " ... aborting installation.");
  2063.           throw e;
  2064.         }
  2065.       }
  2066.       itemLocationTrash.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  2067.       // Move the pointer file to the trash.
  2068.       moveFile(pointerFile, itemLocationTrash);
  2069.     }
  2070.   }
  2071.  
  2072.   // Now tell the client to do their stuff.
  2073.   try {
  2074.     installCallback.callback(itemID, installLocation, installCallback.data);
  2075.   }
  2076.   catch (e) {
  2077.     // This means the install operation failed. Remove everything and roll back.
  2078.     ERROR("safeInstallOperation: install operation (caller-supplied callback) failed, " +
  2079.           "rolling back file moves and aborting installation.");
  2080.     try {
  2081.       // Us-generated. Safe.
  2082.       removeDirRecursive(itemLocation);
  2083.     }
  2084.     catch (e) {
  2085.       ERROR("safeInstallOperation: failed to remove the folder we failed to install " +
  2086.             "an item into: " + itemLocation.path + " -- There is not much to suggest " +
  2087.             "here... maybe restart and try again?");
  2088.       cleanUpTrash(itemLocationTrash);
  2089.       throw e;
  2090.     }
  2091.     rollbackMove();
  2092.     cleanUpTrash(itemLocationTrash);
  2093.     throw e;
  2094.   }
  2095.  
  2096.   // Now, and only now - after everything else has succeeded (against all odds!)
  2097.   // remove the {GUID}-trash directory where we stashed the old version of the
  2098.   // item.
  2099.   cleanUpTrash(itemLocationTrash);
  2100. }
  2101.  
  2102. /**
  2103.  * Manages the list of pending operations.
  2104.  */
  2105. var PendingOperations = {
  2106.   _ops: { },
  2107.  
  2108.   /**
  2109.    * Adds an entry to the Pending Operations List
  2110.    * @param   opType
  2111.    *          The type of Operation to be performed
  2112.    * @param   entry
  2113.    *          A JS Object representing the item to be operated on:
  2114.    *          "locationKey"   The name of the Install Location where the item
  2115.    *                          is installed.
  2116.    *          "id"            The GUID of the item.
  2117.    */
  2118.   addItem: function(opType, entry) {
  2119.     if (opType == OP_NONE)
  2120.       this.clearOpsForItem(entry.id);
  2121.     else {
  2122.       if (!(opType in this._ops))
  2123.         this._ops[opType] = { };
  2124.       this._ops[opType][entry.id] = entry.locationKey;
  2125.     }
  2126.   },
  2127.  
  2128.   /**
  2129.    * Removes a Pending Operation from the list
  2130.    * @param   opType
  2131.    *          The type of Operation being removed
  2132.    * @param   id
  2133.    *          The GUID of the item to remove the entry for
  2134.    */
  2135.   clearItem: function(opType, id) {
  2136.     if (opType in this._ops && id in this._ops[opType])
  2137.       delete this._ops[opType][id];
  2138.   },
  2139.  
  2140.   /**
  2141.    * Removes all Pending Operation for an item
  2142.    * @param   id
  2143.    *          The ID of the item to remove the entries for
  2144.    */
  2145.   clearOpsForItem: function(id) {
  2146.     for (var opType in this._ops) {
  2147.       if (id in this._ops[opType])
  2148.         delete this._ops[opType][id];
  2149.     }
  2150.   },
  2151.  
  2152.   /**
  2153.    * Remove all Pending Operations of a certain type
  2154.    * @param   opType
  2155.    *          The type of Operation to remove all entries for
  2156.    */
  2157.   clearItems: function(opType) {
  2158.     if (opType in this._ops)
  2159.       delete this._ops[opType];
  2160.   },
  2161.  
  2162.   /**
  2163.    * Get an array of operations of a certain type
  2164.    * @param   opType
  2165.    *          The type of Operation to return a list of
  2166.    */
  2167.   getOperations: function(opType) {
  2168.     if (!(opType in this._ops))
  2169.       return [];
  2170.     var ops = [];
  2171.     for (var id in this._ops[opType])
  2172.       ops.push( {id: id, locationKey: this._ops[opType][id] } );
  2173.     return ops;
  2174.   },
  2175.  
  2176.   /**
  2177.    * The total number of Pending Operations, for all types.
  2178.    */
  2179.   get size() {
  2180.     var size = 0;
  2181.     for (var opType in this._ops) {
  2182.       for (var id in this._ops[opType])
  2183.         ++size;
  2184.     }
  2185.     return size;
  2186.   }
  2187. };
  2188.  
  2189. /**
  2190.  * Manages registered Install Locations
  2191.  */
  2192. var InstallLocations = {
  2193.   _locations: { },
  2194.  
  2195.   /**
  2196.    * A nsISimpleEnumerator of all available Install Locations.
  2197.    */
  2198.   get enumeration() {
  2199.     var installLocations = [];
  2200.     for (var key in this._locations)
  2201.       installLocations.push(InstallLocations.get(key));
  2202.     return new ArrayEnumerator(installLocations);
  2203.   },
  2204.  
  2205.   /**
  2206.    * Gets a named Install Location
  2207.    * @param   name
  2208.    *          The name of the Install Location to get
  2209.    */
  2210.   get: function(name) {
  2211.     return name in this._locations ? this._locations[name] : null;
  2212.   },
  2213.  
  2214.   /**
  2215.    * Registers an Install Location
  2216.    * @param   installLocation
  2217.    *          The Install Location to register
  2218.    */
  2219.   put: function(installLocation) {
  2220.     this._locations[installLocation.name] = installLocation;
  2221.   }
  2222. };
  2223.  
  2224. /**
  2225.  * Manages the Startup Cache. The Startup Cache is a representation
  2226.  * of the contents of extensions.cache, a list of all
  2227.  * items the Extension System knows about, whether or not they
  2228.  * are active or visible.
  2229.  */
  2230. var StartupCache = {
  2231.   /**
  2232.    * Location Name -> GUID hash of entries from the Startup Cache file
  2233.    * Each entry has the following properties:
  2234.    *  "descriptor"    The location on disk of the item
  2235.    *  "mtime"         The time the location was last modified
  2236.    *  "op"            Any pending operations on this item.
  2237.    *  "location"      The Install Location name where the item is installed.
  2238.    */
  2239.   entries: { },
  2240.  
  2241.   /**
  2242.    * Puts an entry into the Startup Cache
  2243.    * @param   installLocation
  2244.    *          The Install Location where the item is installed
  2245.    * @param   id
  2246.    *          The GUID of the item
  2247.    * @param   op
  2248.    *          The name of the operation to be performed
  2249.    * @param   shouldCreate
  2250.    *          Whether or not we should create a new entry for this item
  2251.    *          in the cache if one does not already exist.
  2252.    */
  2253.   put: function(installLocation, id, op, shouldCreate) {
  2254.     var itemLocation = installLocation.getItemLocation(id);
  2255.  
  2256.     var descriptor = null;
  2257.     var mtime = null;
  2258.     if (itemLocation) {
  2259.       itemLocation.QueryInterface(Ci.nsILocalFile);
  2260.       descriptor = getDescriptorFromFile(itemLocation, installLocation);
  2261.       if (itemLocation.exists() && itemLocation.isDirectory())
  2262.         mtime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2263.     }
  2264.  
  2265.     this._putRaw(installLocation.name, id, descriptor, mtime, op, shouldCreate);
  2266.   },
  2267.  
  2268.   /**
  2269.    * Private helper function for putting an entry into the Startup Cache
  2270.    * without relying on the presence of its associated nsIInstallLocation
  2271.    * instance.
  2272.    *
  2273.    * @param key
  2274.    *        The install location name.
  2275.    * @param id
  2276.    *        The ID of the item.
  2277.    * @param descriptor
  2278.    *        Value returned from absoluteDescriptor.  May be null, in which
  2279.    *        case the descriptor field is not updated.
  2280.    * @param mtime
  2281.    *        The last modified time of the item.  May be null, in which case the
  2282.    *        descriptor field is not updated.
  2283.    * @param op
  2284.    *        The OP code to store with the entry.
  2285.    * @param shouldCreate
  2286.    *        Boolean value indicating whether to create or delete the entry.
  2287.    */
  2288.   _putRaw: function(key, id, descriptor, mtime, op, shouldCreate) {
  2289.     if (!(key in this.entries))
  2290.       this.entries[key] = { };
  2291.     if (!(id in this.entries[key]))
  2292.       this.entries[key][id] = { };
  2293.     if (shouldCreate) {
  2294.       if (!this.entries[key][id])
  2295.         this.entries[key][id] = { };
  2296.  
  2297.       var entry = this.entries[key][id];
  2298.  
  2299.       if (descriptor)
  2300.         entry.descriptor = descriptor;
  2301.       if (mtime)
  2302.         entry.mtime = mtime;
  2303.       entry.op = op;
  2304.       entry.location = key;
  2305.     }
  2306.     else
  2307.       this.entries[key][id] = null;
  2308.   },
  2309.  
  2310.   /**
  2311.    * Clears an entry from the Startup Cache
  2312.    * @param   installLocation
  2313.    *          The Install Location where item is installed
  2314.    * @param   id
  2315.    *          The GUID of the item.
  2316.    */
  2317.   clearEntry: function(installLocation, id) {
  2318.     var key = installLocation.name;
  2319.     if (key in this.entries && id in this.entries[key])
  2320.       this.entries[key][id] = null;
  2321.   },
  2322.  
  2323.   /**
  2324.    * Get all the startup cache entries for a particular ID.
  2325.    * @param   id
  2326.    *          The GUID of the item to locate.
  2327.    * @returns An array of Startup Cache entries for the specified ID.
  2328.    */
  2329.   findEntries: function(id) {
  2330.     var entries = [];
  2331.     for (var key in this.entries) {
  2332.       if (id in this.entries[key])
  2333.         entries.push(this.entries[key][id]);
  2334.     }
  2335.     return entries;
  2336.   },
  2337.  
  2338.   /**
  2339.    * Read the Item-Change manifest file into a hash of properties.
  2340.    * The Item-Change manifest currently holds a list of paths, with the last
  2341.    * mtime for each path, and the GUID of the item at that path.
  2342.    */
  2343.   read: function() {
  2344.     var itemChangeManifest = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2345.     if (!itemChangeManifest.exists()) {
  2346.       // There is no change manifest for some reason, either we're in an initial
  2347.       // state or something went wrong with one of the other files and the
  2348.       // change manifest was removed. Return an empty dataset and rebuild.
  2349.       gFirstRun = true;
  2350.       return;
  2351.     }
  2352.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  2353.               createInstance(Ci.nsIFileInputStream);
  2354.     fis.init(itemChangeManifest, -1, -1, false);
  2355.     if (fis instanceof Ci.nsILineInputStream) {
  2356.       var line = { value: "" };
  2357.       var more = false;
  2358.       do {
  2359.         more = fis.readLine(line);
  2360.         if (line.value) {
  2361.           // The Item-Change manifest is formatted like so:
  2362.           //  (pd = descriptor)
  2363.           // location-key\tguid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2364.           // location-key\tguid-of-item\tpd-to-extension2\tmtime-of-pd\tpending-op
  2365.           // ...
  2366.           // We hash on location-key first, because we don't want to have to
  2367.           // spin up the main extensions datasource on every start to determine
  2368.           // the Install Location for an item.
  2369.           // We hash on guid second, because we want a way to quickly determine
  2370.           // item GUID during a check loop that runs on every startup.
  2371.           var parts = line.value.split("\t");
  2372.           // Silently drop any entries in unknown install locations
  2373.           if (!InstallLocations.get(parts[0]))
  2374.             continue;
  2375.           var op = parts[4];
  2376.           this._putRaw(parts[0], parts[1], parts[2], parts[3], op, true);
  2377.           if (op)
  2378.             PendingOperations.addItem(op, { locationKey: parts[0], id: parts[1] });
  2379.         }
  2380.       }
  2381.       while (more);
  2382.     }
  2383.     fis.close();
  2384.   },
  2385.  
  2386.   /**
  2387.    * Writes the Startup Cache to disk
  2388.    */
  2389.   write: function() {
  2390.     var extensionsCacheFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2391.     var fos = openSafeFileOutputStream(extensionsCacheFile);
  2392.     for (var locationKey in this.entries) {
  2393.       for (var id in this.entries[locationKey]) {
  2394.         var entry = this.entries[locationKey][id];
  2395.         if (entry) {
  2396.           try {
  2397.             var itemLocation = getFileFromDescriptor(entry.descriptor, InstallLocations.get(locationKey));
  2398.  
  2399.             // Update our knowledge of this item's last-modified-time.
  2400.             // XXXdarin: this may cause us to miss changes in some cases.
  2401.             var itemMTime = 0;
  2402.             if (itemLocation.exists() && itemLocation.isDirectory())
  2403.               itemMTime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2404.  
  2405.             // Each line in the startup cache manifest is in this form:
  2406.             // location-key\tid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2407.             var line = locationKey + "\t" + id + "\t" + entry.descriptor + "\t" +
  2408.                        itemMTime + "\t" + entry.op + "\r\n";
  2409.             fos.write(line, line.length);
  2410.           }
  2411.           catch (e) {}
  2412.         }
  2413.       }
  2414.     }
  2415.     closeSafeFileOutputStream(fos);
  2416.   }
  2417. };
  2418.  
  2419. /**
  2420.  * Installs, manages and tracks compatibility for Extensions and Themes
  2421.  * @constructor
  2422.  */
  2423. function ExtensionManager() {
  2424.   gApp = Cc["@mozilla.org/xre/app-info;1"].
  2425.          getService(Ci.nsIXULAppInfo).QueryInterface(Ci.nsIXULRuntime);
  2426.   gOSTarget = gApp.OS;
  2427.   try {
  2428.     gXPCOMABI = gApp.XPCOMABI;
  2429.   } catch (ex) {
  2430.     // Provide a default for gXPCOMABI. It won't be compared to an
  2431.     // item's metadata (i.e. install.rdf can't specify e.g. WINNT_unknownABI
  2432.     // as targetPlatform), but it will be displayed in error messages and
  2433.     // transmitted to update URLs.
  2434.     gXPCOMABI = UNKNOWN_XPCOM_ABI;
  2435.   }
  2436.   gPref = Cc["@mozilla.org/preferences-service;1"].
  2437.           getService(Ci.nsIPrefBranch2);
  2438.  
  2439.   gOS = Cc["@mozilla.org/observer-service;1"].
  2440.         getService(Ci.nsIObserverService);
  2441.   gOS.addObserver(this, "xpcom-shutdown", false);
  2442.  
  2443.   gConsole = Cc["@mozilla.org/consoleservice;1"].
  2444.              getService(Ci.nsIConsoleService);
  2445.  
  2446.   gRDF = Cc["@mozilla.org/rdf/rdf-service;1"].
  2447.          getService(Ci.nsIRDFService);
  2448.   gInstallManifestRoot = gRDF.GetResource(RDFURI_INSTALL_MANIFEST_ROOT);
  2449.  
  2450.   // Register Global Install Location
  2451.   var appGlobalExtensions = getDirNoCreate(KEY_APPDIR, [DIR_EXTENSIONS]);
  2452.   var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL;
  2453.   var globalLocation = new DirectoryInstallLocation(KEY_APP_GLOBAL,
  2454.                                                     appGlobalExtensions, true,
  2455.                                                     priority, false);
  2456.   InstallLocations.put(globalLocation);
  2457.  
  2458.   // Register App-Profile Install Location
  2459.   var appProfileExtensions = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS]);
  2460.   var priority = Ci.nsIInstallLocation.PRIORITY_APP_PROFILE;
  2461.   var profileLocation = new DirectoryInstallLocation(KEY_APP_PROFILE,
  2462.                                                      appProfileExtensions, false,
  2463.                                                      priority, false);
  2464.   InstallLocations.put(profileLocation);
  2465.  
  2466.   // Register per-user Install Location
  2467.   try {
  2468.     var appSystemUExtensions = getDirNoCreate("XREUSysExt", [gApp.ID]);
  2469.   }
  2470.   catch(e) { }
  2471.  
  2472.   if (appSystemUExtensions) {
  2473.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_USER;
  2474.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_USER,
  2475.                                                       appSystemUExtensions, false,
  2476.                                                       priority, true);
  2477.  
  2478.     InstallLocations.put(systemLocation);
  2479.   }
  2480.  
  2481.   // Register App-System-Shared Install Location
  2482.   try {
  2483.     var appSystemSExtensions = getDirNoCreate("XRESysSExtPD", [gApp.ID]);
  2484.   }
  2485.   catch (e) { }
  2486.  
  2487.   if (appSystemSExtensions) {
  2488.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 10;
  2489.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_SHARE,
  2490.                                                       appSystemSExtensions, true,
  2491.                                                       priority, true);
  2492.     InstallLocations.put(systemLocation);
  2493.   }
  2494.  
  2495.   // Register App-System-Local Install Location
  2496.   try {
  2497.     var appSystemLExtensions = getDirNoCreate("XRESysLExtPD", [gApp.ID]);
  2498.   }
  2499.   catch (e) { }
  2500.  
  2501.   if (appSystemLExtensions) {
  2502.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 20;
  2503.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_LOCAL,
  2504.                                                       appSystemLExtensions, true,
  2505.                                                       priority, true);
  2506.     InstallLocations.put(systemLocation);
  2507.   }
  2508.  
  2509. //@line 2488 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2510.   // Register HKEY_LOCAL_MACHINE Install Location
  2511.   InstallLocations.put(
  2512.       new WinRegInstallLocation("winreg-app-global",
  2513.                                 nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
  2514.                                 true,
  2515.                                 Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 10));
  2516.  
  2517.   // Register HKEY_CURRENT_USER Install Location
  2518.   InstallLocations.put(
  2519.       new WinRegInstallLocation("winreg-app-user",
  2520.                                 nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
  2521.                                 false,
  2522.                                 Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_USER + 10));
  2523. //@line 2502 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2524.  
  2525.   // Register Additional Install Locations
  2526.   var categoryManager = Cc["@mozilla.org/categorymanager;1"].
  2527.                         getService(Ci.nsICategoryManager);
  2528.   var locations = categoryManager.enumerateCategory(CATEGORY_INSTALL_LOCATIONS);
  2529.   while (locations.hasMoreElements()) {
  2530.     var entry = locations.getNext().QueryInterface(Ci.nsISupportsCString).data;
  2531.     var contractID = categoryManager.getCategoryEntry(CATEGORY_INSTALL_LOCATIONS, entry);
  2532.     var location = Cc[contractID].getService(Ci.nsIInstallLocation);
  2533.     InstallLocations.put(location);
  2534.   }
  2535. }
  2536.  
  2537. ExtensionManager.prototype = {
  2538.   /**
  2539.    * See nsIObserver.idl
  2540.    */
  2541.   observe: function(subject, topic, data) {
  2542.     switch (topic) {
  2543.     case "app-startup":
  2544.       gOS.addObserver(this, "profile-after-change", false);
  2545.       gOS.addObserver(this, "quit-application", false);
  2546.       break;
  2547.     case "profile-after-change":
  2548.       this._profileSelected();
  2549.       break;
  2550.     case "quit-application-requested":
  2551.       this._confirmCancelDownloadsOnQuit(subject);
  2552.       break;
  2553.     case "offline-requested":
  2554.       this._confirmCancelDownloadsOnOffline(subject);
  2555.       break;
  2556.     case "quit-application":
  2557.       gOS.removeObserver(this, "profile-after-change");
  2558.       gOS.removeObserver(this, "quit-application");
  2559.       break;
  2560.     case "xpcom-shutdown":
  2561.       this._shutdown();
  2562.       break;
  2563.     case "nsPref:changed":
  2564.       if (data == PREF_EM_LOGGING_ENABLED)
  2565.         this._loggingToggled();
  2566.       else if (data == PREF_EM_CHECK_COMPATIBILITY ||
  2567.                data == PREF_EM_CHECK_UPDATE_SECURITY)
  2568.         this._updateAppDisabledState();
  2569.       else if ((data == PREF_MATCH_OS_LOCALE) || (data == PREF_SELECTED_LOCALE))
  2570.         this._updateLocale();
  2571.       break;
  2572.     }
  2573.   },
  2574.  
  2575.   /**
  2576.    * Refresh the logging enabled global from preferences when the user changes
  2577.    * the preference settting.
  2578.    */
  2579.   _loggingToggled: function() {
  2580.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2581.   },
  2582.  
  2583.   /**
  2584.    * Retrieves the current locale
  2585.    */
  2586.   _updateLocale: function() {
  2587.     try {
  2588.       if (gPref.getBoolPref(PREF_MATCH_OS_LOCALE)) {
  2589.         var localeSvc = Cc["@mozilla.org/intl/nslocaleservice;1"].
  2590.                         getService(Ci.nsILocaleService);
  2591.         gLocale = localeSvc.getLocaleComponentForUserAgent();
  2592.         return;
  2593.       }
  2594.     }
  2595.     catch (ex) {
  2596.     }
  2597.     gLocale = gPref.getCharPref(PREF_SELECTED_LOCALE);
  2598.   },
  2599.  
  2600.   /**
  2601.    * When a preference is toggled that affects whether an item is usable or not
  2602.    * we must app-enable or app-disable the item based on the new settings.
  2603.    */
  2604.   _updateAppDisabledState: function() {
  2605.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2606.     gCheckUpdateSecurity = getPref("getBoolPref", PREF_EM_CHECK_UPDATE_SECURITY, true);
  2607.     var ds = this.datasource;
  2608.  
  2609.     // Enumerate all items
  2610.     var ctr = getContainer(ds, ds._itemRoot);
  2611.     var elements = ctr.GetElements();
  2612.     while (elements.hasMoreElements()) {
  2613.       var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  2614.  
  2615.       // App disable or enable items as necessary
  2616.       // _appEnableItem and _appDisableItem will do nothing if the item is already
  2617.       // in the right state.
  2618.       id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  2619.       if (this._isUsableItem(id))
  2620.         this._appEnableItem(id);
  2621.       else
  2622.         this._appDisableItem(id);
  2623.     }
  2624.   },
  2625.  
  2626.   /**
  2627.    * Initialize the system after a profile has been selected.
  2628.    */
  2629.   _profileSelected: function() {
  2630.     // Tell the Chrome Registry which Skin to select
  2631.     try {
  2632.       if (gPref.getBoolPref(PREF_DSS_SWITCHPENDING)) {
  2633.         var toSelect = gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  2634.         gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, toSelect);
  2635.         gPref.clearUserPref(PREF_DSS_SWITCHPENDING);
  2636.         gPref.clearUserPref(PREF_DSS_SKIN_TO_SELECT);
  2637.       }
  2638.     }
  2639.     catch (e) {
  2640.     }
  2641.  
  2642.     if ("nsICrashReporter" in Ci && gApp instanceof Ci.nsICrashReporter) {
  2643.       // Annotate the crash report with the list of add-ons
  2644.       try {
  2645.         try {
  2646.           gApp.annotateCrashReport("Add-ons", gPref.getCharPref(PREF_EM_ENABLED_ITEMS));
  2647.         } catch (e) { }
  2648.         gApp.annotateCrashReport("Theme", gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN));
  2649.       }
  2650.       catch (ex) {
  2651.         // This will fail in unnofficial builds, ignorable error
  2652.       }
  2653.     }
  2654.  
  2655.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2656.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2657.     gCheckUpdateSecurity = getPref("getBoolPref", PREF_EM_CHECK_UPDATE_SECURITY, true);
  2658.     gPref.addObserver("extensions.", this, false);
  2659.     gPref.addObserver(PREF_MATCH_OS_LOCALE, this, false);
  2660.     gPref.addObserver(PREF_SELECTED_LOCALE, this, false);
  2661.     this._updateLocale();
  2662.   },
  2663.  
  2664.   /**
  2665.    * Notify user that there are new addons updates
  2666.    */
  2667.   _showUpdatesWindow: function() {
  2668.     if (!getPref("getBoolPref", PREF_UPDATE_NOTIFYUSER, false))
  2669.       return;
  2670.  
  2671.     const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  2672.     const EMFEATURES = "chrome,centerscreen,extra-chrome,dialog,resizable,modal";
  2673.  
  2674.     var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  2675.              getService(Ci.nsIWindowWatcher);
  2676.     var param = Cc["@mozilla.org/supports-array;1"].
  2677.                 createInstance(Ci.nsISupportsArray);
  2678.     var arg = Cc["@mozilla.org/supports-string;1"].
  2679.               createInstance(Ci.nsISupportsString);
  2680.     arg.data = "updates-only";
  2681.     param.AppendElement(arg);
  2682.     ww.openWindow(null, EMURL, null, EMFEATURES, param);
  2683.   },
  2684.  
  2685.   /**
  2686.    * Clean up on application shutdown to avoid leaks.
  2687.    */
  2688.   _shutdown: function() {
  2689.     if (!gAllowFlush) {
  2690.       // Something went wrong and there are potentially flushes pending.
  2691.       ERROR("Reached _shutdown and without clearing any pending flushes");
  2692.       try {
  2693.         gAllowFlush = true;
  2694.         if (gManifestNeedsFlush) {
  2695.           gManifestNeedsFlush = false;
  2696.           this._updateManifests(false);
  2697.         }
  2698.         if (gDSNeedsFlush) {
  2699.           gDSNeedsFlush = false;
  2700.           this.datasource.Flush();
  2701.         }
  2702.       }
  2703.       catch (e) {
  2704.         ERROR("Error flushing caches: " + e);
  2705.       }
  2706.     }
  2707.  
  2708.     gOS.removeObserver(this, "xpcom-shutdown");
  2709.  
  2710.     // Release strongly held services.
  2711.     gOS = null;
  2712.     if (this._ptr && gRDF) {
  2713.       gRDF.UnregisterDataSource(this._ptr);
  2714.       this._ptr = null;
  2715.     }
  2716.     gRDF = null;
  2717.     if (gPref) {
  2718.       gPref.removeObserver("extensions.", this);
  2719.       gPref.removeObserver(PREF_MATCH_OS_LOCALE, this);
  2720.       gPref.removeObserver(PREF_SELECTED_LOCALE, this);
  2721.     }
  2722.     gPref = null;
  2723.     gConsole = null;
  2724.     gVersionChecker = null;
  2725.     gInstallManifestRoot = null;
  2726.     gApp = null;
  2727.   },
  2728.  
  2729.   /**
  2730.    * Check for presence of critical Extension system files. If any is missing,
  2731.    * delete the others and signal that the system needs to rebuild them all
  2732.    * from scratch.
  2733.    * @returns true if any critical file is missing and the system needs to
  2734.    *          be rebuilt, false otherwise.
  2735.    */
  2736.   _ensureDatasetIntegrity: function () {
  2737.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  2738.     var extensionsINI = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2739.     var extensionsCache = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2740.  
  2741.     var dsExists = extensionsDS.exists();
  2742.     var iniExists = extensionsINI.exists();
  2743.     var cacheExists = extensionsCache.exists();
  2744.  
  2745.     if (dsExists && iniExists && cacheExists)
  2746.       return false;
  2747.  
  2748.     // If any of the files are missing, remove the .ini file
  2749.     if (iniExists)
  2750.       extensionsINI.remove(false);
  2751.  
  2752.     // If the extensions datasource is missing remove the .cache file if it exists
  2753.     if (!dsExists && cacheExists)
  2754.       extensionsCache.remove(false);
  2755.  
  2756.     return true;
  2757.   },
  2758.  
  2759.   /**
  2760.    * See nsIExtensionManager.idl
  2761.    */
  2762.   start: function(commandLine) {
  2763.     var isDirty = false;
  2764.     var forceAutoReg = false;
  2765.  
  2766.     // Somehow the component list went away, and for that reason the new one
  2767.     // generated by this function is going to result in a different compreg.
  2768.     // We must force a restart.
  2769.     var componentList = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2770.     if (!componentList.exists())
  2771.       forceAutoReg = true;
  2772.  
  2773.     // Check for missing manifests - e.g. missing extensions.ini, missing
  2774.     // extensions.cache, extensions.rdf etc. If any of these files
  2775.     // is missing then we are in some kind of weird or initial state and need
  2776.     // to force a regeneration.
  2777.     if (this._ensureDatasetIntegrity())
  2778.       isDirty = true;
  2779.  
  2780.     // Block attempts to flush for the entire startup
  2781.     gAllowFlush = false;
  2782.  
  2783.     // Configure any items that are being installed, uninstalled or upgraded
  2784.     // by being added, removed or modified by another process. We must do this
  2785.     // on every startup since there is no way we can tell if this has happened
  2786.     // or not!
  2787.     if (this._checkForFileChanges())
  2788.       isDirty = true;
  2789.  
  2790.     this._showUpdatesWindow();
  2791.  
  2792.     if (PendingOperations.size != 0)
  2793.       isDirty = true;
  2794.  
  2795.     var needsRestart = false;
  2796.     // Extension Changes
  2797.     if (isDirty) {
  2798.       needsRestart = this._finishOperations();
  2799.  
  2800.       if (forceAutoReg) {
  2801.         this._extensionListChanged = true;
  2802.         needsRestart = true;
  2803.       }
  2804.     }
  2805.  
  2806.     // Resume flushing and perform a flush for anything that was deferred
  2807.     try {
  2808.       gAllowFlush = true;
  2809.       if (gManifestNeedsFlush) {
  2810.         gManifestNeedsFlush = false;
  2811.         this._updateManifests(false);
  2812.       }
  2813.       if (gDSNeedsFlush) {
  2814.         gDSNeedsFlush = false;
  2815.         this.datasource.Flush();
  2816.       }
  2817.     }
  2818.     catch (e) {
  2819.       ERROR("Error flushing caches: " + e);
  2820.     }
  2821.  
  2822.     if (!needsRestart)
  2823.       this._startTimers();
  2824.  
  2825.     return needsRestart;
  2826.   },
  2827.  
  2828.   /**
  2829.    * Begins all background update check timers
  2830.    */
  2831.   _startTimers: function() {
  2832.     // Register a background update check timer
  2833.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  2834.              getService(Ci.nsIUpdateTimerManager);
  2835.     var interval = getPref("getIntPref", PREF_EM_UPDATE_INTERVAL, 86400);
  2836.     tm.registerTimer("addon-background-update-timer", this, interval);
  2837.   },
  2838.  
  2839.   /**
  2840.    * Notified when a timer fires
  2841.    * @param   timer
  2842.    *          The timer that fired
  2843.    */
  2844.   notify: function(timer) {
  2845.     if (!getPref("getBoolPref", PREF_EM_UPDATE_ENABLED, true))
  2846.       return;
  2847.  
  2848.     var items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  2849.  
  2850.     var updater = new ExtensionItemUpdater(this);
  2851.     updater.checkForUpdates(items, items.length,
  2852.                             Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION,
  2853.                             new BackgroundUpdateCheckListener(this.datasource));
  2854.   },
  2855.  
  2856.   /**
  2857.    * See nsIExtensionManager.idl
  2858.    */
  2859.   handleCommandLineArgs: function(commandLine) {
  2860.     try {
  2861.       var globalExtension = commandLine.handleFlagWithParam("install-global-extension", false);
  2862.       if (globalExtension) {
  2863.         var file = commandLine.resolveFile(globalExtension);
  2864.         this._installGlobalItem(file);
  2865.       }
  2866.       var globalTheme = commandLine.handleFlagWithParam("install-global-theme", false);
  2867.       if (globalTheme) {
  2868.         file = commandLine.resolveFile(globalTheme);
  2869.         this._installGlobalItem(file);
  2870.       }
  2871.     }
  2872.     catch (e) {
  2873.       ERROR("ExtensionManager:handleCommandLineArgs - failure, catching exception - lineno: " +
  2874.             e.lineNumber + " - file: " + e.fileName + " - " + e);
  2875.     }
  2876.     commandLine.preventDefault = true;
  2877.   },
  2878.  
  2879.   /**
  2880.    * Installs an XPI/JAR file into the KEY_APP_GLOBAL install location.
  2881.    * @param   file
  2882.    *          The XPI/JAR file to extract
  2883.    */
  2884.   _installGlobalItem: function(file) {
  2885.     if (!file || !file.exists())
  2886.       throw new Error("Unable to find the file specified on the command line!");
  2887. //@line 2866 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2888.     // make sure the file is local on Windows
  2889.     file.normalize();
  2890.     if (file.path[1] != ':')
  2891.       throw new Error("Can't install global chrome from non-local file "+file.path);
  2892. //@line 2871 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2893.     var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2894.     if (!installManifestFile.exists())
  2895.       throw new Error("The package is missing an install manifest!");
  2896.     var installManifest = getInstallManifest(installManifestFile);
  2897.     installManifestFile.remove(false);
  2898.     var installData = this._getInstallData(installManifest);
  2899.     var installer = new Installer(installManifest, installData.id,
  2900.                                   InstallLocations.get(KEY_APP_GLOBAL),
  2901.                                   installData.type);
  2902.     installer._installExtensionFiles(file);
  2903.     if (installData.type == Ci.nsIUpdateItem.TYPE_THEME)
  2904.       installer.upgradeThemeChrome();
  2905.     else
  2906.       installer.upgradeExtensionChrome();
  2907.   },
  2908.  
  2909.   /**
  2910.    * Check to see if a file is a XPI/JAR file that the user dropped into this
  2911.    * Install Location. (i.e. a XPI that is not a staged XPI from an install
  2912.    * transaction that is currently in operation).
  2913.    * @param   file
  2914.    *          The XPI/JAR file to configure
  2915.    * @param   location
  2916.    *          The Install Location where this file was found.
  2917.    * @returns A nsIUpdateItem representing the dropped XPI if this file was a
  2918.    *          XPI/JAR that needs installation, null otherwise.
  2919.    */
  2920.   _getItemForDroppedFile: function(file, location) {
  2921.     if (fileIsItemPackage(file)) {
  2922.       // We know nothing about this item, it is not something we've
  2923.       // staged in preparation for finalization, so assume it's something
  2924.       // the user dropped in.
  2925.       LOG("A Item Package appeared at: " + file.path + " that we know " +
  2926.           "nothing about, assuming it was dropped in by the user and " +
  2927.           "configuring for installation now. Location Key: " + location.name);
  2928.  
  2929.       var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2930.       if (!installManifestFile.exists())
  2931.         return null;
  2932.       var installManifest = getInstallManifest(installManifestFile);
  2933.       installManifestFile.remove(false);
  2934.       var ds = this.datasource;
  2935.       var installData = this._getInstallData(installManifest);
  2936.       var targetAppInfo = ds.getTargetApplicationInfo(installData.id, installManifest);
  2937.       return makeItem(installData.id,
  2938.                       installData.version,
  2939.                       location.name,
  2940.                       targetAppInfo ? targetAppInfo.minVersion : "",
  2941.                       targetAppInfo ? targetAppInfo.maxVersion : "",
  2942.                       getManifestProperty(installManifest, "name"),
  2943.                       "", /* XPI Update URL */
  2944.                       "", /* XPI Update Hash */
  2945.                       getManifestProperty(installManifest, "iconURL"),
  2946.                       getManifestProperty(installManifest, "updateURL"),
  2947.                       getManifestProperty(installManifest, "updateKey"),
  2948.                       installData.type,
  2949.                       targetAppInfo ? targetAppInfo.appID : gApp.ID);
  2950.     }
  2951.     return null;
  2952.   },
  2953.  
  2954.   /**
  2955.    * Configure an item that was installed or upgraded by another process
  2956.    * so that |_finishOperations| can properly complete processing and
  2957.    * registration.
  2958.    * As this is the only point at which we can reliably know the Install
  2959.    * Location of this item, we use this as an opportunity to:
  2960.    * 1. Check that this item is compatible with this Firefox version.
  2961.    * 2. If it is, configure the item by using the supplied callback.
  2962.    *    We do not do any special handling in the case that the item is
  2963.    *    not compatible with this version other than to simply not register
  2964.    *    it and log that fact - there is no "phone home" check for updates.
  2965.    *    It may or may not make sense to do this, but for now we'll just
  2966.    *    not register.
  2967.    * @param   id
  2968.    *          The GUID of the item to validate and configure.
  2969.    * @param   location
  2970.    *          The Install Location where this item is installed.
  2971.    * @param   callback
  2972.    *          The callback that configures the item for installation upon
  2973.    *          successful validation.
  2974.    */
  2975.    installItem: function(id, location, callback) {
  2976.     // As this is the only pint at which we reliably know the installation
  2977.     var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  2978.     if (installRDF.exists()) {
  2979.       LOG("Item Installed/Upgraded at Install Location: " + location.name +
  2980.           " Item ID: " + id + ", attempting to register...");
  2981.       var installManifest = getInstallManifest(installRDF);
  2982.       var installData = this._getInstallData(installManifest);
  2983.       if (installData.error == INSTALLERROR_SUCCESS) {
  2984.         LOG("... success, item is compatible");
  2985.         callback(installManifest, installData.id, location, installData.type);
  2986.       }
  2987.       else if (installData.error == INSTALLERROR_INCOMPATIBLE_VERSION) {
  2988.         LOG("... success, item installed but is not compatible");
  2989.         callback(installManifest, installData.id, location, installData.type);
  2990.         this._appDisableItem(id);
  2991.       }
  2992.       else if (installData.error == INSTALLERROR_INSECURE_UPDATE) {
  2993.         LOG("... success, item installed but does not provide updates securely");
  2994.         callback(installManifest, installData.id, location, installData.type);
  2995.         this._appDisableItem(id);
  2996.       }
  2997.       else if (installData.error == INSTALLERROR_BLOCKLISTED) {
  2998.         LOG("... success, item installed but is blocklisted");
  2999.         callback(installManifest, installData.id, location, installData.type);
  3000.         this._appDisableItem(id);
  3001.       }
  3002.       else {
  3003.         /**
  3004.          * Turns an error code into a message for logging
  3005.          * @param   error
  3006.          *          an Install Error code
  3007.          * @returns A string message to be logged.
  3008.          */
  3009.         function translateErrorMessage(error) {
  3010.           switch (error) {
  3011.           case INSTALLERROR_INVALID_GUID:
  3012.             return "Invalid GUID";
  3013.           case INSTALLERROR_INVALID_VERSION:
  3014.             return "Invalid Version";
  3015.           case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  3016.             return "Incompatible Platform";
  3017.           }
  3018.         }
  3019.         LOG("... failure, item is not compatible, error: " +
  3020.             translateErrorMessage(installData.error));
  3021.  
  3022.         // Add the item to the Startup Cache anyway, so we don't re-detect it
  3023.         // every time the app starts.
  3024.         StartupCache.put(location, id, OP_NONE, true);
  3025.       }
  3026.     }
  3027.   },
  3028.  
  3029.   /**
  3030.    * Check for changes to items that were made independently of the Extension
  3031.    * Manager, e.g. items were added or removed from a Install Location or items
  3032.    * in an Install Location changed.
  3033.    */
  3034.   _checkForFileChanges: function() {
  3035.     var em = this;
  3036.  
  3037.     /**
  3038.      * Determines if an item can be used based on whether or not the install
  3039.      * location of the "item" has an equal or higher priority than the install
  3040.      * location where another version may live.
  3041.      * @param   id
  3042.      *          The GUID of the item being installed.
  3043.      * @param   location
  3044.      *          The location where an item is to be installed.
  3045.      * @returns true if the item can be installed at that location, false
  3046.      *          otherwise.
  3047.      */
  3048.     function canUse(id, location) {
  3049.       for (var locationKey in StartupCache.entries) {
  3050.         if (locationKey != location.name &&
  3051.             id in StartupCache.entries[locationKey]) {
  3052.           if (StartupCache.entries[locationKey][id]) {
  3053.             var oldInstallLocation = InstallLocations.get(locationKey);
  3054.             if (oldInstallLocation.priority <= location.priority)
  3055.               return false;
  3056.           }
  3057.         }
  3058.       }
  3059.       return true;
  3060.     }
  3061.  
  3062.     /**
  3063.       * Gets a Dialog Param Block loaded with a set of strings to initialize the
  3064.       * XPInstall Confirmation Dialog.
  3065.       * @param   strings
  3066.       *          An array of strings
  3067.       * @returns A nsIDialogParamBlock loaded with the strings and dialog state.
  3068.       */
  3069.     function getParamBlock(strings) {
  3070.       var dpb = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  3071.                 createInstance(Ci.nsIDialogParamBlock);
  3072.       // OK and Cancel Buttons
  3073.       dpb.SetInt(0, 2);
  3074.       // Number of Strings
  3075.       dpb.SetInt(1, strings.length);
  3076.       dpb.SetNumberStrings(strings.length);
  3077.       // Add Strings
  3078.       for (var i = 0; i < strings.length; ++i)
  3079.         dpb.SetString(i, strings[i]);
  3080.  
  3081.       var supportsString = Cc["@mozilla.org/supports-string;1"].
  3082.                            createInstance(Ci.nsISupportsString);
  3083.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  3084.       supportsString.data = bundle.GetStringFromName("droppedInWarning");
  3085.       var objs = Cc["@mozilla.org/array;1"].
  3086.                  createInstance(Ci.nsIMutableArray);
  3087.       objs.appendElement(supportsString, false);
  3088.       dpb.objects = objs;
  3089.       return dpb;
  3090.     }
  3091.  
  3092.     /**
  3093.      * Installs a set of files which were dropped into an install location by
  3094.      * the user, only after user confirmation.
  3095.      * @param   droppedInFiles
  3096.      *          An array of JS objects with the following properties:
  3097.      *          "file"      The nsILocalFile where the XPI lives
  3098.      *          "location"  The Install Location where the XPI was found.
  3099.      * @param   xpinstallStrings
  3100.      *          An array of strings used to initialize the XPInstall Confirm
  3101.      *          dialog.
  3102.      */
  3103.     function installDroppedInFiles(droppedInFiles, xpinstallStrings) {
  3104.       if (droppedInFiles.length == 0)
  3105.         return;
  3106.  
  3107.       var dpb = getParamBlock(xpinstallStrings);
  3108.       var ifptr = Cc["@mozilla.org/supports-interface-pointer;1"].
  3109.                   createInstance(Ci.nsISupportsInterfacePointer);
  3110.       ifptr.data = dpb;
  3111.       ifptr.dataIID = Ci.nsIDialogParamBlock;
  3112.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  3113.                getService(Ci.nsIWindowWatcher);
  3114.       ww.openWindow(null, URI_XPINSTALL_CONFIRM_DIALOG,
  3115.                     "", "chrome,centerscreen,modal,dialog,titlebar", ifptr);
  3116.       if (!dpb.GetInt(0)) {
  3117.         // User said OK - install items
  3118.         for (var i = 0; i < droppedInFiles.length; ++i) {
  3119.           em.installItemFromFile(droppedInFiles[i].file,
  3120.                                  droppedInFiles[i].location.name);
  3121.           // We are responsible for cleaning up this file
  3122.           droppedInFiles[i].file.remove(false);
  3123.         }
  3124.       }
  3125.       else {
  3126.         for (i = 0; i < droppedInFiles.length; ++i) {
  3127.           // We are responsible for cleaning up this file
  3128.           droppedInFiles[i].file.remove(false);
  3129.         }
  3130.       }
  3131.     }
  3132.  
  3133.     var isDirty = false;
  3134.     var ignoreMTimeChanges = getPref("getBoolPref", PREF_EM_IGNOREMTIMECHANGES,
  3135.                                      false);
  3136.     StartupCache.read();
  3137.  
  3138.     // Array of objects with 'location' and 'id' properties to maybe install.
  3139.     var newItems = [];
  3140.  
  3141.     var droppedInFiles = [];
  3142.     var xpinstallStrings = [];
  3143.  
  3144.     // Enumerate over the install locations from low to high priority.  The
  3145.     // enumeration returned is pre-sorted.
  3146.     var installLocations = this.installLocations;
  3147.     while (installLocations.hasMoreElements()) {
  3148.       var location = installLocations.getNext().QueryInterface(Ci.nsIInstallLocation);
  3149.  
  3150.       // Hash the set of items actually held by the Install Location.
  3151.       var actualItems = { };
  3152.       var entries = location.itemLocations;
  3153.       while (true) {
  3154.         var entry = entries.nextFile;
  3155.         if (!entry)
  3156.           break;
  3157.  
  3158.         // Is this location a valid item? It must be a directory, and contain
  3159.         // an install.rdf manifest:
  3160.         if (entry.isDirectory()) {
  3161.           var installRDF = entry.clone();
  3162.           installRDF.append(FILE_INSTALL_MANIFEST);
  3163.  
  3164.           var id = location.getIDForLocation(entry);
  3165.           if (!id || (!installRDF.exists() &&
  3166.                       !location.itemIsManagedIndependently(id)))
  3167.             continue;
  3168.  
  3169.           actualItems[id] = entry;
  3170.         }
  3171.         else {
  3172.           // Check to see if this file is a XPI/JAR dropped into this dir
  3173.           // by the user, installing it if necessary. We do this here rather
  3174.           // than separately in |_finishOperations| because I don't want to
  3175.           // walk these lists multiple times on every startup.
  3176.           var item = this._getItemForDroppedFile(entry, location);
  3177.           if (item) {
  3178.             droppedInFiles.push({ file: entry, location: location });
  3179.             var prettyName = "";
  3180.             try {
  3181.               var zipReader = getZipReaderForFile(entry);
  3182.               var principal = { };
  3183.               var certPrincipal = zipReader.getCertificatePrincipal(null, principal);
  3184.               // XXXbz This string could be empty.  This needs better
  3185.               // UI to present principal.value.certificate's subject.
  3186.               prettyName = principal.value.prettyName;
  3187.             }
  3188.             catch (e) { }
  3189.             if (zipReader)
  3190.               zipReader.close();
  3191.             xpinstallStrings = xpinstallStrings.concat([item.name,
  3192.                                                         getURLSpecFromFile(entry),
  3193.                                                         item.iconURL,
  3194.                                                         prettyName]);
  3195.             isDirty = true;
  3196.           }
  3197.         }
  3198.       }
  3199.  
  3200.       if (location.name in StartupCache.entries) {
  3201.         // Look for items that have been uninstalled by removing their directory.
  3202.         for (var id in StartupCache.entries[location.name]) {
  3203.           if (!StartupCache.entries[location.name] ||
  3204.               !StartupCache.entries[location.name][id])
  3205.             continue;
  3206.  
  3207.           // Force _finishOperations to run if we have enabled or disabled items.
  3208.           // XXXdarin this should be unnecessary now that we check
  3209.           // PendingOperations.size in start()
  3210.           if (StartupCache.entries[location.name][id].op == OP_NEEDS_ENABLE ||
  3211.               StartupCache.entries[location.name][id].op == OP_NEEDS_DISABLE)
  3212.             isDirty = true;
  3213.  
  3214.           if (!(id in actualItems) &&
  3215.               StartupCache.entries[location.name][id].op != OP_NEEDS_UNINSTALL &&
  3216.               StartupCache.entries[location.name][id].op != OP_NEEDS_INSTALL &&
  3217.               StartupCache.entries[location.name][id].op != OP_NEEDS_UPGRADE) {
  3218.             // We have an entry for this id in the Extensions database, for this
  3219.             // install location, but it no longer exists in the Install Location.
  3220.             // We can infer from this that the item has been removed, so uninstall
  3221.             // it properly.
  3222.             if (canUse(id, location)) {
  3223.               LOG("Item Uninstalled via file removal from: " + StartupCache.entries[location.name][id].descriptor +
  3224.                   " Item ID: " + id + " Location Key: " + location.name + ", uninstalling item.");
  3225.  
  3226.               // Load the Extensions Datasource and force this item into the visible
  3227.               // items list if it is not already. This allows us to handle the case
  3228.               // where there is an entry for an item in the Startup Cache but not
  3229.               // in the extensions.rdf file - in that case the item will not be in
  3230.               // the visible list and calls to |getInstallLocation| will mysteriously
  3231.               // fail.
  3232.               this.datasource.updateVisibleList(id, location.name, false);
  3233.               this.uninstallItem(id);
  3234.               isDirty = true;
  3235.             }
  3236.           }
  3237.           else if (!ignoreMTimeChanges) {
  3238.             // Look for items whose mtime has changed, and as such we can assume
  3239.             // they have been "upgraded".
  3240.             var lf = { path: StartupCache.entries[location.name][id].descriptor };
  3241.             try {
  3242.                lf = getFileFromDescriptor(StartupCache.entries[location.name][id].descriptor, location);
  3243.             }
  3244.             catch (e) { }
  3245.  
  3246.             if (lf.exists && lf.exists()) {
  3247.               var actualMTime = Math.floor(lf.lastModifiedTime / 1000);
  3248.               if (actualMTime != StartupCache.entries[location.name][id].mtime) {
  3249.                 LOG("Item Location path changed: " + lf.path + " Item ID: " +
  3250.                     id + " Location Key: " + location.name + ", attempting to upgrade item...");
  3251.                 if (canUse(id, location)) {
  3252.                   this.installItem(id, location,
  3253.                                    function(installManifest, id, location, type) {
  3254.                                      em._upgradeItem(installManifest, id, location,
  3255.                                                      type);
  3256.                                    });
  3257.                   isDirty = true;
  3258.                 }
  3259.               }
  3260.             }
  3261.             else {
  3262.               isDirty = true;
  3263.               LOG("Install Location returned a missing or malformed item path! " +
  3264.                   "Item Path: " + lf.path + ", Location Key: " + location.name +
  3265.                   " Item ID: " + id);
  3266.               if (canUse(id, location)) {
  3267.                 // Load the Extensions Datasource and force this item into the visible
  3268.                 // items list if it is not already. This allows us to handle the case
  3269.                 // where there is an entry for an item in the Startup Cache but not
  3270.                 // in the extensions.rdf file - in that case the item will not be in
  3271.                 // the visible list and calls to |getInstallLocation| will mysteriously
  3272.                 // fail.
  3273.                 this.datasource.updateVisibleList(id, location.name, false);
  3274.                 this.uninstallItem(id);
  3275.               }
  3276.             }
  3277.           }
  3278.         }
  3279.       }
  3280.  
  3281.       // Look for items that have been installed by appearing in the location.
  3282.       for (var id in actualItems) {
  3283.         if (!(location.name in StartupCache.entries) ||
  3284.             !(id in StartupCache.entries[location.name]) ||
  3285.             !StartupCache.entries[location.name][id]) {
  3286.           // Remember that we've seen this item
  3287.           StartupCache.put(location, id, OP_NONE, true);
  3288.           // Push it on the stack of items to maybe install later
  3289.           newItems.push({location: location, id: id});
  3290.         }
  3291.       }
  3292.     }
  3293.  
  3294.     // Process any newly discovered items.  We do this here instead of in the
  3295.     // previous loop so that we can be sure that we have a fully populated
  3296.     // StartupCache.
  3297.     for (var i = 0; i < newItems.length; ++i) {
  3298.       var id = newItems[i].id;
  3299.       var location = newItems[i].location;
  3300.       if (canUse(id, location)) {
  3301.         LOG("Item Installed via directory addition to Install Location: " +
  3302.             location.name + " Item ID: " + id + ", attempting to register...");
  3303.         this.installItem(id, location,
  3304.                          function(installManifest, id, location, type) {
  3305.                            em._configureForthcomingItem(installManifest, id, location,
  3306.                                                         type);
  3307.                          });
  3308.         // Disable add-ons on install when the InstallDisabled file exists.
  3309.         // This is so Talkback will be disabled on a subset of installs.
  3310.         var installDisabled = location.getItemFile(id, "InstallDisabled");
  3311.         if (installDisabled.exists())
  3312.           em.disableItem(id);
  3313.         isDirty = true;
  3314.       }
  3315.     }
  3316.  
  3317.     // Ask the user if they want to install the dropped items, for security
  3318.     // purposes.
  3319.     installDroppedInFiles(droppedInFiles, xpinstallStrings);
  3320.  
  3321.     return isDirty;
  3322.   },
  3323.  
  3324.   /**
  3325.    * Upgrades contents.rdf files to chrome.manifest files for any existing
  3326.    * Extensions and Themes.
  3327.    * @returns true if actions were performed that require a restart, false
  3328.    *          otherwise.
  3329.    */
  3330.   _upgradeChrome: function() {
  3331.     if (inSafeMode())
  3332.       return false;
  3333.  
  3334.     var checkForNewChrome = false;
  3335.     var ds = this.datasource;
  3336.     // If we have extensions that were installed before the new flat chrome
  3337.     // manifests, and are still valid, we need to manually create the flat
  3338.     // manifest files.
  3339.     var extensions = this._getActiveItems(Ci.nsIUpdateItem.TYPE_EXTENSION +
  3340.                                           Ci.nsIUpdateItem.TYPE_LOCALE);
  3341.     for (var i = 0; i < extensions.length; ++i) {
  3342.       var e = extensions[i];
  3343.       var itemLocation = e.location.getItemLocation(e.id);
  3344.       var manifest = itemLocation.clone();
  3345.       manifest.append(FILE_CHROME_MANIFEST);
  3346.       if (!manifest.exists()) {
  3347.         var installRDF = itemLocation.clone();
  3348.         installRDF.append(FILE_INSTALL_MANIFEST);
  3349.         var installLocation = this.getInstallLocation(e.id);
  3350.         if (installLocation && installRDF.exists()) {
  3351.           var itemLocation = installLocation.getItemLocation(e.id);
  3352.           if (itemLocation.exists() && itemLocation.isDirectory()) {
  3353.             var installer = new Installer(ds, e.id, installLocation,
  3354.                                           Ci.nsIUpdateItem.TYPE_EXTENSION);
  3355.             installer.upgradeExtensionChrome();
  3356.           }
  3357.         }
  3358.         else {
  3359.           ds.removeItemMetadata(e.id);
  3360.           ds.removeItemFromContainer(e.id);
  3361.         }
  3362.  
  3363.         checkForNewChrome = true;
  3364.       }
  3365.     }
  3366.  
  3367.     var themes = this._getActiveItems(Ci.nsIUpdateItem.TYPE_THEME);
  3368.     // If we have themes that were installed before the new flat chrome
  3369.     // manifests, and are still valid, we need to manually create the flat
  3370.     // manifest files.
  3371.     for (i = 0; i < themes.length; ++i) {
  3372.       var item = themes[i];
  3373.       var itemLocation = item.location.getItemLocation(item.id);
  3374.       var manifest = itemLocation.clone();
  3375.       manifest.append(FILE_CHROME_MANIFEST);
  3376.       if (manifest.exists() ||
  3377.           item.id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  3378.         continue;
  3379.  
  3380.       var entries;
  3381.       try {
  3382.         var manifestURI = getURIFromFile(manifest);
  3383.         var chromeDir = itemLocation.clone();
  3384.         chromeDir.append(DIR_CHROME);
  3385.  
  3386.         if (!chromeDir.exists() || !chromeDir.isDirectory()) {
  3387.           ds.removeItemMetadata(item.id);
  3388.           ds.removeItemFromContainer(item.id);
  3389.           continue;
  3390.         }
  3391.  
  3392.         // We're relying on the fact that there is only one JAR file
  3393.         // in the "chrome" directory. This is a hack, but it works.
  3394.         entries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  3395.         var jarFile = entries.nextFile;
  3396.         if (jarFile) {
  3397.           var jarFileURI = getURIFromFile(jarFile);
  3398.           var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  3399.  
  3400.           // Use the Chrome Registry API to install the theme there
  3401.           var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  3402.                    getService(Ci.nsIToolkitChromeRegistry);
  3403.           cr.processContentsManifest(contentsURI, manifestURI, contentsURI, false, true);
  3404.         }
  3405.         entries.close();
  3406.       }
  3407.       catch (e) {
  3408.         ERROR("_upgradeChrome: failed to upgrade contents manifest for " +
  3409.               "theme: " + item.id + ", exception: " + e + "... The theme will be " +
  3410.               "disabled.");
  3411.         this._appDisableItem(item.id);
  3412.       }
  3413.       finally {
  3414.         try {
  3415.           entries.close();
  3416.         }
  3417.         catch (e) {
  3418.         }
  3419.       }
  3420.       checkForNewChrome = true;
  3421.     }
  3422.     return checkForNewChrome;
  3423.   },
  3424.  
  3425.   _checkForUncoveredItem: function(id) {
  3426.     var ds = this.datasource;
  3427.     var oldLocation = this.getInstallLocation(id);
  3428.     var newLocations = [];
  3429.     for (var locationKey in StartupCache.entries) {
  3430.       var location = InstallLocations.get(locationKey);
  3431.       if (id in StartupCache.entries[locationKey] &&
  3432.           location.priority > oldLocation.priority)
  3433.         newLocations.push(location);
  3434.     }
  3435.     newLocations.sort(function(a, b) { return b.priority - a.priority; });
  3436.     if (newLocations.length > 0) {
  3437.       for (var i = 0; i < newLocations.length; ++i) {
  3438.         // Check to see that the item at the location exists
  3439.         var installRDF = newLocations[i].getItemFile(id, FILE_INSTALL_MANIFEST);
  3440.         if (installRDF.exists()) {
  3441.           // Update the visible item cache so that |_finalizeUpgrade| is properly
  3442.           // called from |_finishOperations|
  3443.           var name = newLocations[i].name;
  3444.           ds.updateVisibleList(id, name, true);
  3445.           PendingOperations.addItem(OP_NEEDS_UPGRADE,
  3446.                                     { locationKey: name, id: id });
  3447.           PendingOperations.addItem(OP_NEEDS_INSTALL,
  3448.                                     { locationKey: name, id: id });
  3449.           break;
  3450.         }
  3451.         else {
  3452.           // If no item exists at the location specified, remove this item
  3453.           // from the visible items list and check again.
  3454.           StartupCache.clearEntry(newLocations[i], id);
  3455.           ds.updateVisibleList(id, null, true);
  3456.         }
  3457.       }
  3458.     }
  3459.     else
  3460.       ds.updateVisibleList(id, null, true);
  3461.   },
  3462.  
  3463.   /**
  3464.    * Finish up pending operations - perform upgrades, installs, enables/disables,
  3465.    * uninstalls etc.
  3466.    * @returns true if actions were performed that require a restart, false
  3467.    *          otherwise.
  3468.    */
  3469.   _finishOperations: function() {
  3470.     try {
  3471.       // Stuff has changed, load the Extensions datasource in all its RDFey
  3472.       // glory.
  3473.       var ds = this.datasource;
  3474.       var updatedTargetAppInfos = [];
  3475.  
  3476.       var needsRestart = false;
  3477.       var upgrades = [];
  3478.       var newAddons = [];
  3479.       var addons = getPref("getCharPref", PREF_EM_NEW_ADDONS_LIST, "");
  3480.       if (addons != "")
  3481.         newAddons = addons.split(",");
  3482.       do {
  3483.         // Enable and disable during startup so items that are changed in the
  3484.         // ui can be reset to a no-op.
  3485.         // Look for extensions that need to be enabled.
  3486.         var items = PendingOperations.getOperations(OP_NEEDS_ENABLE);
  3487.         for (var i = items.length - 1; i >= 0; --i) {
  3488.           var id = items[i].id;
  3489.           var installLocation = this.getInstallLocation(id);
  3490.           StartupCache.put(installLocation, id, OP_NONE, true);
  3491.           PendingOperations.clearItem(OP_NEEDS_ENABLE, id);
  3492.           needsRestart = true;
  3493.         }
  3494.         PendingOperations.clearItems(OP_NEEDS_ENABLE);
  3495.  
  3496.         // Look for extensions that need to be disabled.
  3497.         items = PendingOperations.getOperations(OP_NEEDS_DISABLE);
  3498.         for (i = items.length - 1; i >= 0; --i) {
  3499.           id = items[i].id;
  3500.           installLocation = this.getInstallLocation(id);
  3501.           StartupCache.put(installLocation, id, OP_NONE, true);
  3502.           PendingOperations.clearItem(OP_NEEDS_DISABLE, id);
  3503.           needsRestart = true;
  3504.         }
  3505.         PendingOperations.clearItems(OP_NEEDS_DISABLE);
  3506.  
  3507.         // Look for extensions that need to be upgraded. The process here is to
  3508.         // uninstall the old version of the extension first, then install the
  3509.         // new version in its place.
  3510.         items = PendingOperations.getOperations(OP_NEEDS_UPGRADE);
  3511.         for (i = items.length - 1; i >= 0; --i) {
  3512.           id = items[i].id;
  3513.           var newLocation = InstallLocations.get(items[i].locationKey);
  3514.           // check if there is updated app compatibility info
  3515.           var newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3516.           if (newTargetAppInfo)
  3517.             updatedTargetAppInfos.push(newTargetAppInfo);
  3518.           this._finalizeUpgrade(id, newLocation);
  3519.           upgrades.push(id);
  3520.         }
  3521.         PendingOperations.clearItems(OP_NEEDS_UPGRADE);
  3522.  
  3523.         // Install items
  3524.         items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3525.         for (i = items.length - 1; i >= 0; --i) {
  3526.           needsRestart = true;
  3527.           id = items[i].id;
  3528.           // check if there is updated app compatibility info
  3529.           newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3530.           if (newTargetAppInfo)
  3531.             updatedTargetAppInfos.push(newTargetAppInfo);
  3532.           this._finalizeInstall(id, null);
  3533.           if (upgrades.indexOf(id) < 0 && newAddons.indexOf(id) < 0)
  3534.             newAddons.push(id);
  3535.         }
  3536.         PendingOperations.clearItems(OP_NEEDS_INSTALL);
  3537.  
  3538.         // Look for extensions that need to be removed. This MUST be done after
  3539.         // the install operations since extensions to be installed may have to be
  3540.         // uninstalled if there are errors during the installation process!
  3541.         items = PendingOperations.getOperations(OP_NEEDS_UNINSTALL);
  3542.         for (i = items.length - 1; i >= 0; --i) {
  3543.           id = items[i].id;
  3544.           this._finalizeUninstall(id);
  3545.           this._checkForUncoveredItem(id);
  3546.           needsRestart = true;
  3547.           var pos = newAddons.indexOf(id);
  3548.           if (pos >= 0)
  3549.             newAddons.splice(pos, 1);
  3550.         }
  3551.         PendingOperations.clearItems(OP_NEEDS_UNINSTALL);
  3552.  
  3553.         // When there have been operations and all operations have completed.
  3554.         if (PendingOperations.size == 0) {
  3555.           // If there is updated app compatibility info update the datasource.
  3556.           for (i = 0; i < updatedTargetAppInfos.length; ++i)
  3557.             ds.setTargetApplicationInfo(updatedTargetAppInfos[i].id,
  3558.                                         updatedTargetAppInfos[i].targetAppID,
  3559.                                         updatedTargetAppInfos[i].minVersion,
  3560.                                         updatedTargetAppInfos[i].maxVersion,
  3561.                                         null);
  3562.  
  3563.           // Enumerate all items
  3564.           var ctr = getContainer(ds, ds._itemRoot);
  3565.           var elements = ctr.GetElements();
  3566.           while (elements.hasMoreElements()) {
  3567.             var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  3568.  
  3569.             // Ensure appDisabled is in the correct state.
  3570.             id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3571.             if (this._isUsableItem(id))
  3572.               ds.setItemProperty(id, EM_R("appDisabled"), null);
  3573.             else
  3574.               ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  3575.  
  3576.             // userDisabled is set based on its value being OP_NEEDS_ENABLE or
  3577.             // OP_NEEDS_DISABLE. This allows us to have an item to be enabled
  3578.             // by the app and disabled by the user during a single restart.
  3579.             var value = stringData(ds.GetTarget(itemResource, EM_R("userDisabled"), true));
  3580.             if (value == OP_NEEDS_ENABLE)
  3581.               ds.setItemProperty(id, EM_R("userDisabled"), null);
  3582.             else if (value == OP_NEEDS_DISABLE)
  3583.               ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  3584.           }
  3585.         }
  3586.       }
  3587.       while (PendingOperations.size > 0);
  3588.  
  3589.       // Upgrade contents.rdf files to the new chrome.manifest format for
  3590.       // existing Extensions and Themes
  3591.       if (this._upgradeChrome()) {
  3592.         var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  3593.                  getService(Ci.nsIChromeRegistry);
  3594.         cr.checkForNewChrome();
  3595.       }
  3596.  
  3597.       // If no additional restart is required, it implies that there are
  3598.       // no new components that need registering so we can inform the app
  3599.       // not to do any extra startup checking next time round.
  3600.       this._updateManifests(needsRestart);
  3601.  
  3602.       // Remember the list of add-ons that were installed this time around
  3603.       // unless this was a new profile.
  3604.       if (!gFirstRun && newAddons.length > 0)
  3605.         gPref.setCharPref(PREF_EM_NEW_ADDONS_LIST, newAddons.join(","));
  3606.     }
  3607.     catch (e) {
  3608.       ERROR("ExtensionManager:_finishOperations - failure, catching exception - lineno: " +
  3609.             e.lineNumber + " - file: " + e.fileName + " - " + e);
  3610.     }
  3611.     return needsRestart;
  3612.   },
  3613.  
  3614.   /**
  3615.    * Checks to see if there are items that are incompatible with this version
  3616.    * of the application, disables them to prevent incompatibility problems and
  3617.    * invokes the Update Wizard to look for newer versions.
  3618.    * @returns true if there were incompatible items installed and disabled, and
  3619.    *          the application must now be restarted to reinitialize XPCOM,
  3620.    *          false otherwise.
  3621.    */
  3622.   checkForMismatches: function() {
  3623.     // Check to see if the version of the application that is being started
  3624.     // now is the same one that was started last time.
  3625.     var currAppVersion = gApp.version;
  3626.     var lastAppVersion = getPref("getCharPref", PREF_EM_LAST_APP_VERSION, "");
  3627.     if (currAppVersion == lastAppVersion)
  3628.       return false;
  3629.     // With a new profile lastAppVersion doesn't exist yet.
  3630.     if (!lastAppVersion) {
  3631.       gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3632.       return false;
  3633.     }
  3634.  
  3635.     // Block attempts to flush for the entire startup
  3636.     gAllowFlush = false;
  3637.  
  3638.     // Version mismatch, we have to load the extensions datasource and do
  3639.     // version checking. Time hit here doesn't matter since this doesn't happen
  3640.     // all that often.
  3641.     this._upgradeFromV10();
  3642.  
  3643.     // Make the extensions datasource consistent if it isn't already.
  3644.     var isDirty = false;
  3645.     if (this._ensureDatasetIntegrity())
  3646.       isDirty = true;
  3647.  
  3648.     if (this._checkForFileChanges())
  3649.       isDirty = true;
  3650.  
  3651.     if (PendingOperations.size != 0)
  3652.       isDirty = true;
  3653.  
  3654.     if (isDirty)
  3655.       this._finishOperations();
  3656.  
  3657.     var ds = this.datasource;
  3658.     // During app upgrade cleanup invalid entries in the extensions datasource.
  3659.     ds.beginUpdateBatch();
  3660.     var allResources = ds.GetAllResources();
  3661.     while (allResources.hasMoreElements()) {
  3662.       var res = allResources.getNext().QueryInterface(Ci.nsIRDFResource);
  3663.       if (ds.GetTarget(res, EM_R("downloadURL"), true) ||
  3664.           (!ds.GetTarget(res, EM_R("installLocation"), true) &&
  3665.           stringData(ds.GetTarget(res, EM_R("appDisabled"), true)) == "true"))
  3666.         ds.removeDownload(res.Value);
  3667.     }
  3668.     ds.endUpdateBatch();
  3669.  
  3670.     var badItems = [];
  3671.     var allAppManaged = true;
  3672.     var ctr = getContainer(ds, ds._itemRoot);
  3673.     var elements = ctr.GetElements();
  3674.     while (elements.hasMoreElements()) {
  3675.       var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  3676.       var id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3677.       var location = this.getInstallLocation(id);
  3678.       if (!location) {
  3679.         // Item was in an unknown install location
  3680.         badItems.push(id);
  3681.         continue;
  3682.       }
  3683.  
  3684.       if (ds.getItemProperty(id, "appManaged") == "true") {
  3685.         // Force an update of the metadata for appManaged extensions since the
  3686.         // last modified time is not updated for directories on FAT / FAT32
  3687.         // filesystems when software update applies a new version of the app.
  3688.         if (location.name == KEY_APP_GLOBAL) {
  3689.           var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3690.           if (installRDF.exists()) {
  3691.             var metadataDS = getInstallManifest(installRDF);
  3692.             ds.addItemMetadata(id, metadataDS, location);
  3693.             ds.updateProperty(id, "compatible");
  3694.           }
  3695.         }
  3696.       }
  3697.       else if (allAppManaged)
  3698.         allAppManaged = false;
  3699.  
  3700.       var properties = {
  3701.         availableUpdateURL: null,
  3702.         availableUpdateVersion: null
  3703.       };
  3704.  
  3705.       if (ds.getItemProperty(id, "providesUpdatesSecurely") == "false") {
  3706.         /* It's possible the previous version did not understand updateKeys so
  3707.          * check if we can import one for this addon from it's manifest. */
  3708.         installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3709.         if (installRDF.exists()) {
  3710.           metadataDS = getInstallManifest(installRDF);
  3711.           var literal = metadataDS.GetTarget(gInstallManifestRoot, EM_R("updateKey"), true);
  3712.           if (literal && literal instanceof Ci.nsIRDFLiteral)
  3713.             ds.setItemProperty(id, EM_R("updateKey"), literal);
  3714.         }
  3715.       }
  3716.  
  3717.       // appDisabled is determined by an item being compatible, using secure
  3718.       // updates, satisfying its dependencies, and not being blocklisted
  3719.       if (this._isUsableItem(id)) {
  3720.         if (ds.getItemProperty(id, "appDisabled"))
  3721.           properties.appDisabled = null;
  3722.       }
  3723.       else if (!ds.getItemProperty(id, "appDisabled")) {
  3724.         properties.appDisabled = EM_L("true");
  3725.       }
  3726.  
  3727.       ds.setItemProperties(id, properties);
  3728.     }
  3729.  
  3730.     // Must clean up outside of the loop. Modifying the container while
  3731.     // iterating its contents is bad.
  3732.     for (var i = 0; i < badItems.length; i++) {
  3733.       id = badItems[i];
  3734.       LOG("Item " + id + " was installed in an unknown location, removing.");
  3735.       var disabled = ds.getItemProperty(id, "userDisabled") == "true";
  3736.       // Clean up the datasource
  3737.       ds.removeCorruptItem(id);
  3738.       // Check for any unhidden items.
  3739.       var entries = StartupCache.findEntries(id);
  3740.       if (entries.length > 0) {
  3741.         var newLocation = InstallLocations.get(entries[0].location);
  3742.         for (var j = 1; j < entries.length; j++) {
  3743.           location = InstallLocations.get(entries[j].location);
  3744.           if (newLocation.priority < location.priority)
  3745.             newLocation = location;
  3746.         }
  3747.         LOG("Activating item " + id + " in " + newLocation.name);
  3748.         var em = this;
  3749.         this.installItem(id, newLocation,
  3750.                          function(installManifest, id, location, type) {
  3751.                            em._configureForthcomingItem(installManifest, id, location,
  3752.                                                         type);
  3753.                          });
  3754.         if (disabled)
  3755.           em.disableItem(id);
  3756.       }
  3757.     }
  3758.  
  3759.     // Update the manifests to reflect the items that were disabled / enabled.
  3760.     this._updateManifests(true);
  3761.  
  3762.     // Always check for compatibility updates when upgrading if we have add-ons
  3763.     // that aren't managed by the application.
  3764.     if (!allAppManaged)
  3765.       this._showMismatchWindow();
  3766.  
  3767.     // Finish any pending upgrades from the compatibility update to avoid an
  3768.     // additional restart.
  3769.     if (PendingOperations.size != 0)
  3770.       this._finishOperations();
  3771.  
  3772.     // Update the last app version so we don't do this again with this version.
  3773.     gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3774.  
  3775.     // Prevent extension update dialog from showing
  3776.     gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  3777.  
  3778.     // Re-enable flushing and flush anything that was deferred
  3779.     try {
  3780.       gAllowFlush = true;
  3781.       if (gManifestNeedsFlush) {
  3782.         gManifestNeedsFlush = false;
  3783.         this._updateManifests(false);
  3784.       }
  3785.       if (gDSNeedsFlush) {
  3786.         gDSNeedsFlush = false;
  3787.         this.datasource.Flush();
  3788.       }
  3789.     }
  3790.     catch (e) {
  3791.       ERROR("Error flushing caches: " + e);
  3792.     }
  3793.  
  3794.     return true;
  3795.   },
  3796.  
  3797.   /**
  3798.    * Shows the "Compatibility Updates" UI
  3799.    */
  3800.   _showMismatchWindow: function(items) {
  3801.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  3802.              getService(Ci.nsIWindowMediator);
  3803.     var wizard = wm.getMostRecentWindow("Update:Wizard");
  3804.     if (wizard)
  3805.       wizard.focus();
  3806.     else {
  3807.       var features = "chrome,centerscreen,dialog,titlebar,modal";
  3808.       // This *must* be modal so as not to break startup! This code is invoked before
  3809.       // the main event loop is initiated (via checkForMismatches).
  3810.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  3811.                getService(Ci.nsIWindowWatcher);
  3812.       ww.openWindow(null, URI_EXTENSION_UPDATE_DIALOG, "", features, null);
  3813.     }
  3814.   },
  3815.  
  3816.   /*
  3817.    * Catch all for facilitating a version 1.0 profile upgrade.
  3818.    * 1) removes the abandoned default theme directory from the profile.
  3819.    * 2) prepares themes installed with version 1.0 for installation.
  3820.    * 3) initiates an install to populate the new extensions datasource.
  3821.    * 4) migrates the disabled attribute from the old datasource.
  3822.    * 5) migrates the app compatibility info from the old datasource.
  3823.    */
  3824.   _upgradeFromV10: function() {
  3825.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  3826.     var dsExists = extensionsDS.exists();
  3827.     // Toolkiit 1.7 profiles (Firefox 1.0, Thunderbird 1.0, etc.) have a default
  3828.     // theme directory in the profile's extensions directory that will be
  3829.     // disabled due to having a maxVersion that is incompatible with the
  3830.     // toolkit 1.8 release of the app.
  3831.     var profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3832.                                              stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)]);
  3833.     if (profileDefaultTheme && profileDefaultTheme.exists()) {
  3834.       removeDirRecursive(profileDefaultTheme);
  3835.       // Sunbird 0.3a1 didn't move the default theme into the app's extensions
  3836.       // directory and we can't install it while uninstalling the one in the
  3837.       // profile directory. If we have a toolkit 1.8 extensions datasource and
  3838.       // a profile default theme deleting the toolkit 1.8 extensions datasource
  3839.       // will fix this problem when the datasource is re-created.
  3840.       if (dsExists)
  3841.         extensionsDS.remove(false);
  3842.     }
  3843.  
  3844.     // return early if the toolkit 1.7 extensions datasource file doesn't exist.
  3845.     var oldExtensionsFile = getFile(KEY_PROFILEDIR, [DIR_EXTENSIONS, "Extensions.rdf"]);
  3846.     if (!oldExtensionsFile.exists())
  3847.       return;
  3848.  
  3849.     // Sunbird 0.2 used a different GUID for the default theme
  3850.     profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3851.                                          "{8af2d0a7-e394-4de2-ae55-2dae532a7a9b}"]);
  3852.     if (profileDefaultTheme && profileDefaultTheme.exists())
  3853.       removeDirRecursive(profileDefaultTheme);
  3854.  
  3855.     // Firefox 0.9 profiles may have DOMi 1.0 with just an install.rdf
  3856.     var profileDOMi = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3857.                                      "{641d8d09-7dda-4850-8228-ac0ab65e2ac9}"]);
  3858.     if (profileDOMi && profileDOMi.exists())
  3859.       removeDirRecursive(profileDOMi);
  3860.  
  3861.     // return early to avoid migrating data twice if we already have a
  3862.     // toolkit 1.8 extension datasource.
  3863.     if (dsExists)
  3864.       return;
  3865.  
  3866.     // Prepare themes for installation
  3867.     // Only enumerate directories in the app-profile and app-global locations.
  3868.     var locations = [KEY_APP_PROFILE, KEY_APP_GLOBAL];
  3869.     for (var i = 0; i < locations.length; ++i) {
  3870.       var location = InstallLocations.get(locations[i]);
  3871.       if (!location.canAccess)
  3872.         continue;
  3873.  
  3874.       var entries = location.itemLocations;
  3875.       var entry;
  3876.       while ((entry = entries.nextFile)) {
  3877.         var installRDF = entry.clone();
  3878.         installRDF.append(FILE_INSTALL_MANIFEST);
  3879.  
  3880.         var chromeDir = entry.clone();
  3881.         chromeDir.append(DIR_CHROME);
  3882.  
  3883.         // It must be a directory without an install.rdf and it must contain
  3884.         // a chrome directory
  3885.         if (!entry.isDirectory() || installRDF.exists() || !chromeDir.exists())
  3886.           continue;
  3887.  
  3888.         var chromeEntries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  3889.         if (!chromeEntries.hasMoreElements())
  3890.           continue;
  3891.  
  3892.         // We're relying on the fact that there is only one JAR file
  3893.         // in the "chrome" directory. This is a hack, but it works.
  3894.         var jarFile = chromeEntries.nextFile;
  3895.         if (jarFile.isDirectory())
  3896.           continue;
  3897.         var id = location.getIDForLocation(entry);
  3898.  
  3899.         try {
  3900.           var zipReader = getZipReaderForFile(jarFile);
  3901.           zipReader.extract(FILE_INSTALL_MANIFEST, installRDF);
  3902.  
  3903.           var contentsManifestFile = location.getItemFile(id, FILE_CONTENTS_MANIFEST);
  3904.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  3905.  
  3906.           var rootFiles = ["preview.png", "icon.png"];
  3907.           for (var i = 0; i < rootFiles.length; ++i) {
  3908.             try {
  3909.               var target = location.getItemFile(id, rootFiles[i]);
  3910.               zipReader.extract(rootFiles[i], target);
  3911.             }
  3912.             catch (e) {
  3913.             }
  3914.           }
  3915.           zipReader.close();
  3916.         }
  3917.         catch (e) {
  3918.           ERROR("ExtensionManager:_upgradeFromV10 - failed to extract theme files\r\n" +
  3919.                 "Exception: " + e);
  3920.         }
  3921.       }
  3922.     }
  3923.  
  3924.     // When upgrading from a version 1.0 profile we need to populate the
  3925.     // extensions datasource with all items before checking for incompatible
  3926.     // items since the datasource hasn't been created yet.
  3927.     var itemsToCheck = [];
  3928.     if (this._checkForFileChanges()) {
  3929.       // Create a list of all items that are to be installed so we can migrate
  3930.       // these items's settings to the new datasource.
  3931.       var items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3932.       for (i = items.length - 1; i >= 0; --i) {
  3933.         if (items[i].locationKey == KEY_APP_PROFILE ||
  3934.             items[i].locationKey == KEY_APP_GLOBAL)
  3935.           itemsToCheck.push(items[i].id);
  3936.       }
  3937.       this._finishOperations();
  3938.     }
  3939.  
  3940.     // If there are no items to migrate settings for return early.
  3941.     if (itemsToCheck.length == 0)
  3942.       return;
  3943.  
  3944.     var fileURL = getURLSpecFromFile(oldExtensionsFile);
  3945.     var oldExtensionsDS = gRDF.GetDataSourceBlocking(fileURL);
  3946.     var versionChecker = getVersionChecker();
  3947.     var ds = this.datasource;
  3948.     var currAppVersion = gApp.version;
  3949.     var currAppID = gApp.ID;
  3950.     for (var i = 0; i < itemsToCheck.length; ++i) {
  3951.       var item = ds.getItemForID(itemsToCheck[i]);
  3952.       var oldPrefix = (item.type == Ci.nsIUpdateItem.TYPE_EXTENSION) ? PREFIX_EXTENSION : PREFIX_THEME;
  3953.       var oldRes = gRDF.GetResource(oldPrefix + item.id);
  3954.       // Disable the item if it was disabled in the version 1.0 extensions
  3955.       // datasource.
  3956.       if (oldExtensionsDS.GetTarget(oldRes, EM_R("disabled"), true))
  3957.         ds.setItemProperty(item.id, EM_R("userDisabled"), EM_L("true"));
  3958.  
  3959.       // app enable all items. If it is incompatible it will be app disabled
  3960.       // later on.
  3961.       ds.setItemProperty(item.id, EM_R("appDisabled"), null);
  3962.  
  3963.       // if the item is already compatible don't attempt to migrate the
  3964.       // item's compatibility info
  3965.       var newRes = getResourceForID(itemsToCheck[i]);
  3966.       if (ds.isCompatible(ds, newRes))
  3967.         continue;
  3968.  
  3969.       var updatedMinVersion = null;
  3970.       var updatedMaxVersion = null;
  3971.       var targetApps = oldExtensionsDS.GetTargets(oldRes, EM_R("targetApplication"), true);
  3972.       while (targetApps.hasMoreElements()) {
  3973.         var targetApp = targetApps.getNext();
  3974.         if (targetApp instanceof Ci.nsIRDFResource) {
  3975.           try {
  3976.             var foundAppID = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("id"), true));
  3977.             // Different target application?  (Note:  v1.0 didn't support toolkit app ID)
  3978.             if (foundAppID != currAppID)
  3979.               continue;
  3980.  
  3981.             updatedMinVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("minVersion"), true));
  3982.             updatedMaxVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("maxVersion"), true));
  3983.  
  3984.             // Only set the target app info if the extension's target app info
  3985.             // in the version 1.0 extensions datasource makes it compatible
  3986.             if (versionChecker.compare(currAppVersion, updatedMinVersion) >= 0 &&
  3987.                 versionChecker.compare(currAppVersion, updatedMaxVersion) <= 0)
  3988.               ds.setTargetApplicationInfo(item.id, foundAppID, updatedMinVersion,
  3989.                                           updatedMaxVersion, null);
  3990.  
  3991.             break;
  3992.           }
  3993.           catch (e) {
  3994.           }
  3995.         }
  3996.       }
  3997.     }
  3998.   },
  3999.  
  4000.   /**
  4001.    * Write the Extensions List and the Startup Cache
  4002.    * @param   needsRestart
  4003.    *          true if the application needs to restart again, false otherwise.
  4004.    */
  4005.   _updateManifests: function(needsRestart) {
  4006.     // During startup we block flushing until the startup operations are all
  4007.     // complete to reduce file accesses that can trigger bug 431065
  4008.     if (gAllowFlush) {
  4009.       // Write the Startup Cache (All Items, visible or not)
  4010.       StartupCache.write();
  4011.       // Write the Extensions Locations Manifest (Visible, enabled items)
  4012.       this._updateExtensionsManifest();
  4013.     }
  4014.     else {
  4015.       gManifestNeedsFlush = true;
  4016.     }
  4017.  
  4018.     // Notify nsAppRunner to update the compatibility manifest on next startup
  4019.     this._extensionListChanged = needsRestart;
  4020.   },
  4021.  
  4022.   /**
  4023.    * Get a list of items that are currently "active" (turned on) of a specific
  4024.    * type
  4025.    * @param   type
  4026.    *          The nsIUpdateItem type to return a list of items of
  4027.    * @returns An array of active items of the specified type.
  4028.    */
  4029.   _getActiveItems: function(type) {
  4030.     var allItems = this.getItemList(type, { });
  4031.     var activeItems = [];
  4032.     var ds = this.datasource;
  4033.     for (var i = 0; i < allItems.length; ++i) {
  4034.       var item = allItems[i];
  4035.  
  4036.       var installLocation = this.getInstallLocation(item.id);
  4037.       // An entry with an invalid install location is not active.
  4038.       if (!installLocation)
  4039.         continue;
  4040.       // An item entry is valid only if it is not disabled, not about to
  4041.       // be disabled, and not about to be uninstalled.
  4042.       if (installLocation.name in StartupCache.entries &&
  4043.           item.id in StartupCache.entries[installLocation.name] &&
  4044.           StartupCache.entries[installLocation.name][item.id]) {
  4045.         var op = StartupCache.entries[installLocation.name][item.id].op;
  4046.         if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE ||
  4047.             op == OP_NEEDS_UNINSTALL || op == OP_NEEDS_DISABLE)
  4048.           continue;
  4049.       }
  4050.       // Suppress items that have been disabled by the user or the app.
  4051.       if (ds.getItemProperty(item.id, "isDisabled") != "true")
  4052.         activeItems.push({ id: item.id, version: item.version,
  4053.                            location: installLocation });
  4054.     }
  4055.  
  4056.     return activeItems;
  4057.   },
  4058.  
  4059.   /**
  4060.    * Write the Extensions List
  4061.    */
  4062.   _updateExtensionsManifest: function() {
  4063.     // When an operation is performed that requires a component re-registration
  4064.     // (extension enabled/disabled, installed, uninstalled), we must write the
  4065.     // set of paths where extensions live so that the startup system can determine
  4066.     // where additional components, preferences, chrome manifests etc live.
  4067.     //
  4068.     // To do this we obtain a list of active extensions and themes and write
  4069.     // these to the extensions.ini file in the profile directory.
  4070.     var validExtensions = this._getActiveItems(Ci.nsIUpdateItem.TYPE_ANY -
  4071.                                                Ci.nsIUpdateItem.TYPE_THEME);
  4072.     var validThemes     = this._getActiveItems(Ci.nsIUpdateItem.TYPE_THEME);
  4073.  
  4074.     var extensionsLocationsFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  4075.     var fos = openSafeFileOutputStream(extensionsLocationsFile);
  4076.  
  4077.     var enabledItems = [];
  4078.     var extensionSectionHeader = "[ExtensionDirs]\r\n";
  4079.     fos.write(extensionSectionHeader, extensionSectionHeader.length);
  4080.     for (var i = 0; i < validExtensions.length; ++i) {
  4081.       var e = validExtensions[i];
  4082.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(Ci.nsILocalFile);
  4083.       var descriptor = getAbsoluteDescriptor(itemLocation);
  4084.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  4085.       fos.write(line, line.length);
  4086.       enabledItems.push(e.id + ":" + e.version);
  4087.     }
  4088.  
  4089.     var themeSectionHeader = "[ThemeDirs]\r\n";
  4090.     fos.write(themeSectionHeader, themeSectionHeader.length);
  4091.     for (i = 0; i < validThemes.length; ++i) {
  4092.       var e = validThemes[i];
  4093.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(Ci.nsILocalFile);
  4094.       var descriptor = getAbsoluteDescriptor(itemLocation);
  4095.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  4096.       fos.write(line, line.length);
  4097.       enabledItems.push(e.id + ":" + e.version);
  4098.     }
  4099.  
  4100.     closeSafeFileOutputStream(fos);
  4101.  
  4102.     // Cache the enabled list for annotating the crash report subsequently
  4103.     gPref.setCharPref(PREF_EM_ENABLED_ITEMS, enabledItems.join(","));
  4104.   },
  4105.  
  4106.   /**
  4107.    * Say whether or not the Extension List has changed (and thus whether or not
  4108.    * the system will have to restart the next time it is started).
  4109.    * @param   val
  4110.    *          true if the Extension List has changed, false otherwise.
  4111.    * @returns |val|
  4112.    */
  4113.   set _extensionListChanged(val) {
  4114.     // When an extension has an operation perform on it (e.g. install, upgrade,
  4115.     // disable, etc.) we are responsible for creating the .autoreg file and
  4116.     // nsAppRunner is responsible for removing it on restart. At some point it
  4117.     // may make sense to be able to cancel a registration but for now we only
  4118.     // create the file.
  4119.     try {
  4120.       var autoregFile = getFile(KEY_PROFILEDIR, [FILE_AUTOREG]);
  4121.       if (val && !autoregFile.exists())
  4122.         autoregFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4123.     }
  4124.     catch (e) {
  4125.     }
  4126.     return val;
  4127.   },
  4128.  
  4129.   /**
  4130.    * Gathers data about an item specified by the supplied Install Manifest
  4131.    * and determines whether or not it can be installed as-is. It makes this
  4132.    * determination by validating the item's GUID, Version, and determining
  4133.    * if it is compatible with this application.
  4134.    * @param   installManifest
  4135.    *          A nsIRDFDataSource representing the Install Manifest of the
  4136.    *          item to be installed.
  4137.    * @return  A JS Object with the following properties:
  4138.    *          "id"       The GUID of the Item being installed.
  4139.    *          "version"  The Version string of the Item being installed.
  4140.    *          "name"     The Name of the Item being installed.
  4141.    *          "type"     The nsIUpdateItem type of the Item being installed.
  4142.    *          "targetApps" An array of TargetApplication Info Objects
  4143.    *                     with "id", "minVersion" and "maxVersion" properties,
  4144.    *                     representing applications targeted by this item.
  4145.    *          "error"    The result code:
  4146.    *                     INSTALLERROR_SUCCESS
  4147.    *                       no error, item can be installed
  4148.    *                     INSTALLERROR_INVALID_GUID
  4149.    *                       error, GUID is not well-formed
  4150.    *                     INSTALLERROR_INVALID_VERSION
  4151.    *                       error, Version is not well-formed
  4152.    *                     INSTALLERROR_INCOMPATIBLE_VERSION
  4153.    *                       error, item is not compatible with this version
  4154.    *                       of the application.
  4155.    *                     INSTALLERROR_INCOMPATIBLE_PLATFORM
  4156.    *                       error, item is not compatible with the operating
  4157.    *                       system or ABI the application was built for.
  4158.    *                     INSTALLERROR_INSECURE_UPDATE
  4159.    *                       error, item has no secure method of providing updates
  4160.    *                     INSTALLERROR_BLOCKLISTED
  4161.    *                       error, item is blocklisted
  4162.    */
  4163.   _getInstallData: function(installManifest) {
  4164.     var installData = { id          : "",
  4165.                         version     : "",
  4166.                         name        : "",
  4167.                         type        : 0,
  4168.                         error       : INSTALLERROR_SUCCESS,
  4169.                         targetApps  : [],
  4170.                         updateURL   : "",
  4171.                         updateKey   : "",
  4172.                         currentApp  : null };
  4173.  
  4174.     // Fetch properties from the Install Manifest
  4175.     installData.id       = getManifestProperty(installManifest, "id");
  4176.     installData.version  = getManifestProperty(installManifest, "version");
  4177.     installData.name     = getManifestProperty(installManifest, "name");
  4178.     installData.type     = getAddonTypeFromInstallManifest(installManifest);
  4179.     installData.updateURL= getManifestProperty(installManifest, "updateURL");
  4180.     installData.updateKey= getManifestProperty(installManifest, "updateKey");
  4181.  
  4182.     /**
  4183.      * Reads a property off a Target Application resource
  4184.      * @param   resource
  4185.      *          The RDF Resource for a Target Application
  4186.      * @param   property
  4187.      *          The property (less EM_NS) to read
  4188.      * @returns The string literal value of the property.
  4189.      */
  4190.     function readTAProperty(resource, property) {
  4191.       return stringData(installManifest.GetTarget(resource, EM_R(property), true));
  4192.     }
  4193.  
  4194.     var targetApps = installManifest.GetTargets(gInstallManifestRoot,
  4195.                                                 EM_R("targetApplication"),
  4196.                                                 true);
  4197.     while (targetApps.hasMoreElements()) {
  4198.       var targetApp = targetApps.getNext();
  4199.       if (targetApp instanceof Ci.nsIRDFResource) {
  4200.         try {
  4201.           var data = { id        : readTAProperty(targetApp, "id"),
  4202.                        minVersion: readTAProperty(targetApp, "minVersion"),
  4203.                        maxVersion: readTAProperty(targetApp, "maxVersion") };
  4204.           installData.targetApps.push(data);
  4205.           if ((data.id == gApp.ID) ||
  4206.               (data.id == TOOLKIT_ID) && !installData.currentApp)
  4207.             installData.currentApp = data;
  4208.         }
  4209.         catch (e) {
  4210.           continue;
  4211.         }
  4212.       }
  4213.     }
  4214.  
  4215.     // If the item specifies one or more target platforms, make sure our OS/ABI
  4216.     // combination is in the list - otherwise, refuse to install the item.
  4217.     var targetPlatforms = null;
  4218.     try {
  4219.       targetPlatforms = installManifest.GetTargets(gInstallManifestRoot,
  4220.                                                    EM_R("targetPlatform"),
  4221.                                                    true);
  4222.     } catch(e) {
  4223.       // No targetPlatform nodes, continue.
  4224.     }
  4225.     if (targetPlatforms != null && targetPlatforms.hasMoreElements()) {
  4226.       var foundMatchingOS = false;
  4227.       var foundMatchingOSAndABI = false;
  4228.       var requireABICompatibility = false;
  4229.       while (targetPlatforms.hasMoreElements()) {
  4230.         var targetPlatform = stringData(targetPlatforms.getNext());
  4231.         var os = targetPlatform.split("_")[0];
  4232.         var index = targetPlatform.indexOf("_");
  4233.         var abi = index != -1 ? targetPlatform.substr(index + 1) : null;
  4234.         if (os == gOSTarget) {
  4235.           foundMatchingOS = true;
  4236.           // The presence of any ABI part after our OS means ABI is important.
  4237.           if (abi != null) {
  4238.             requireABICompatibility = true;
  4239.             // If we don't know our ABI, we can't be compatible
  4240.             if (abi == gXPCOMABI && abi != UNKNOWN_XPCOM_ABI) {
  4241.               foundMatchingOSAndABI = true;
  4242.               break;
  4243.             }
  4244.           }
  4245.         }
  4246.       }
  4247.       if (!foundMatchingOS || (requireABICompatibility && !foundMatchingOSAndABI)) {
  4248.         installData.error = INSTALLERROR_INCOMPATIBLE_PLATFORM;
  4249.         return installData;
  4250.       }
  4251.     }
  4252.  
  4253.     // Validate the Item ID
  4254.     if (!gIDTest.test(installData.id)) {
  4255.       installData.error = INSTALLERROR_INVALID_GUID;
  4256.       return installData;
  4257.     }
  4258.     
  4259.     // Check that the add-on provides a secure update method.
  4260.     if (gCheckUpdateSecurity &&
  4261.         installData.updateURL &&
  4262.         installData.updateURL.substring(0, 6) != "https:" &&
  4263.         !installData.updateKey) {
  4264.       installData.error = INSTALLERROR_INSECURE_UPDATE;
  4265.       return installData;
  4266.     }
  4267.       
  4268.     // Check that the target application range allows compatibility with the app
  4269.     if (gCheckCompatibility &&
  4270.         !this.datasource.isCompatible(installManifest, gInstallManifestRoot, undefined)) {
  4271.       installData.error = INSTALLERROR_INCOMPATIBLE_VERSION;
  4272.       return installData;
  4273.     }
  4274.     
  4275.     // Check if the item is blocklisted.
  4276.     if (!gBlocklist)
  4277.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  4278.                    getService(Ci.nsIBlocklistService);
  4279.     if (gBlocklist.isAddonBlocklisted(installData.id, installData.version,
  4280.                                       null, null))
  4281.       installData.error = INSTALLERROR_BLOCKLISTED;
  4282.  
  4283.     return installData;
  4284.   },
  4285.  
  4286.   /**
  4287.    * Installs an item from a XPI/JAR file.
  4288.    * This is the main entry point into the Install system from outside code
  4289.    * (e.g. XPInstall).
  4290.    * @param   aXPIFile
  4291.    *          The file to install from.
  4292.    * @param   aInstallLocationKey
  4293.    *          The name of the Install Location where this item should be
  4294.    *          installed.
  4295.    */
  4296.   installItemFromFile: function(xpiFile, installLocationKey) {
  4297.     this.installItemFromFileInternal(xpiFile, installLocationKey, null);
  4298.  
  4299.     // If there are no compatibility checks running and no downloads in
  4300.     // progress then the install operations are complete.
  4301.     if (this._compatibilityCheckCount == 0 && this._transactions.length == 0) {
  4302.       for (var i = 0; i < this._installListeners.length; ++i)
  4303.         this._installListeners[i].onInstallsCompleted();
  4304.     }
  4305.   },
  4306.  
  4307.   /**
  4308.    * Installs an item from a XPI/JAR file.
  4309.    * @param   aXPIFile
  4310.    *          The file to install from.
  4311.    * @param   aInstallLocationKey
  4312.    *          The name of the Install Location where this item should be
  4313.    *          installed.
  4314.    * @param   aInstallManifest
  4315.    *          An updated Install Manifest from the Version Update check.
  4316.    *          Can be null when invoked from callers other than the Version
  4317.    *          Update check.
  4318.    */
  4319.   installItemFromFileInternal: function(aXPIFile, aInstallLocationKey, aInstallManifest) {
  4320.     var em = this;
  4321.     /**
  4322.      * Gets the Install Location for an Item.
  4323.      * @param   itemID
  4324.      *          The GUID of the item to find an Install Location for.
  4325.      * @return  An object implementing nsIInstallLocation which represents the
  4326.      *          location where the specified item should be installed.
  4327.      *          This can be:
  4328.      *          1. an object that corresponds to the location key supplied to
  4329.      *             |installItemFromFileInternal|,
  4330.      *          2. the default install location (the App Profile Extensions Folder)
  4331.      *             if no location key was supplied, or the location key supplied
  4332.      *             was not in the set of registered locations
  4333.      *          3. null, if the location selected by 1 or 2 above does not support
  4334.      *             installs from XPI/JAR files, or that location is not writable
  4335.      *             with the current access privileges.
  4336.      */
  4337.     function getInstallLocation(itemID) {
  4338.       // Here I use "upgrade" to mean "install a different version of an item".
  4339.       var installLocation = em.getInstallLocation(itemID);
  4340.       if (!installLocation) {
  4341.         // This is not an "upgrade", since we don't have any location data for the
  4342.         // extension ID specified - that is, it's not in our database.
  4343.  
  4344.         // Caller supplied a key to a registered location, use that location
  4345.         // for the installation
  4346.         installLocation = InstallLocations.get(aInstallLocationKey);
  4347.         if (installLocation) {
  4348.           // If the specified location does not have a common metadata location
  4349.           // (e.g. extensions have no common root, or other location specified
  4350.           // by the location implementation) - e.g. for a Registry Key enumeration
  4351.           // location - we cannot install or upgrade using a XPI file, probably
  4352.           // because these application types will be handling upgrading themselves.
  4353.           // Just bail.
  4354.           if (!installLocation.location) {
  4355.             LOG("Install Location \"" + installLocation.name + "\" does not support " +
  4356.                 "installation of items from XPI/JAR files. You must manage " +
  4357.                 "installation and update of these items yourself.");
  4358.             installLocation = null;
  4359.           }
  4360.         }
  4361.         else {
  4362.           // In the absence of a preferred install location, just default to
  4363.           // the App-Profile
  4364.           installLocation = InstallLocations.get(KEY_APP_PROFILE);
  4365.         }
  4366.       }
  4367.       else {
  4368.         // This is an "upgrade", but not through the Update System, because the
  4369.         // Update code will not let an extension with an incompatible target
  4370.         // app version range through to this point. This is an "upgrade" in the
  4371.         // sense that the user found a different version of an installed extension
  4372.         // and installed it through the web interface, so we have metadata.
  4373.  
  4374.         // If the location is different, return the preferred location rather than
  4375.         // the location of the currently installed version, because we may be in
  4376.         // the situation where an item is being installed into the global app
  4377.         // dir when there's a version in the profile dir.
  4378.         if (installLocation.name != aInstallLocationKey)
  4379.           installLocation = InstallLocations.get(aInstallLocationKey);
  4380.       }
  4381.       if (!installLocation.canAccess) {
  4382.         LOG("Install Location\"" + installLocation.name + "\" cannot be written " +
  4383.             "to with your access privileges. Installation will not proceed.");
  4384.         installLocation = null;
  4385.       }
  4386.       return installLocation;
  4387.     }
  4388.  
  4389.     /**
  4390.      * Stages a XPI file in the default item location specified by other
  4391.      * applications when they registered with XulRunner if the item's
  4392.      * install manifest specified compatibility with them.
  4393.      */
  4394.     function stageXPIForOtherApps(xpiFile, installData) {
  4395.       for (var i = 0; i < installData.targetApps.length; ++i) {
  4396.         var targetApp = installData.targetApps[i];
  4397.         if (targetApp.id != gApp.ID && targetApp.id != TOOLKIT_ID) {
  4398.         /* XXXben uncomment when this works!
  4399.           var settingsThingy = Cc[].
  4400.                                getService(Ci.nsIXULRunnerSettingsThingy);
  4401.           try {
  4402.             var appPrefix = "SOFTWARE\\Mozilla\\XULRunner\\Applications\\";
  4403.             var branch = settingsThingy.getBranch(appPrefix + targetApp.id);
  4404.             var path = branch.getProperty("ExtensionsLocation");
  4405.             var destination = Cc["@mozilla.org/file/local;1"].
  4406.                               createInstance(Ci.nsILocalFile);
  4407.             destination.initWithPath(path);
  4408.             xpiFile.copyTo(file, xpiFile.leafName);
  4409.           }
  4410.           catch (e) {
  4411.           }
  4412.          */
  4413.         }
  4414.       }
  4415.     }
  4416.  
  4417.     /**
  4418.      * Extracts and then starts the install for extensions / themes contained
  4419.      * within a xpi.
  4420.      */
  4421.     function installMultiXPI(xpiFile, installData) {
  4422.       var fileURL = getURIFromFile(xpiFile).QueryInterface(Ci.nsIURL);
  4423.       if (fileURL.fileExtension.toLowerCase() != "xpi") {
  4424.         LOG("Invalid File Extension: Item: \"" + fileURL.fileName + "\" has an " +
  4425.             "invalid file extension. Only xpi file extensions are allowed for " +
  4426.             "multiple item packages.");
  4427.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4428.         showMessage("invalidFileExtTitle", [],
  4429.                     "invalidFileExtMessage", [installData.name,
  4430.                     fileURL.fileExtension,
  4431.                     bundle.GetStringFromName("type-" + installData.type)]);
  4432.         return;
  4433.       }
  4434.  
  4435.       try {
  4436.         var zipReader = getZipReaderForFile(xpiFile);
  4437.       }
  4438.       catch (e) {
  4439.         LOG("installMultiXPI: failed to open xpi file: " + xpiFile.path);
  4440.         throw e;
  4441.       }
  4442.  
  4443.       var searchForEntries = ["*.xpi", "*.jar"];
  4444.       var files = [];
  4445.       for (var i = 0; i < searchForEntries.length; ++i) {
  4446.         var entries = zipReader.findEntries(searchForEntries[i]);
  4447.         while (entries.hasMore()) {
  4448.           var entryName = entries.getNext();
  4449.           var target = getFile(KEY_TEMPDIR, [entryName]);
  4450.           try {
  4451.             target.createUnique(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4452.           }
  4453.           catch (e) {
  4454.             LOG("installMultiXPI: failed to create target file for extraction " +
  4455.                 " file = " + target.path + ", exception = " + e + "\n");
  4456.           }
  4457.           zipReader.extract(entryName, target);
  4458.           files.push(target);
  4459.         }
  4460.       }
  4461.       zipReader.close();
  4462.  
  4463.       if (files.length == 0) {
  4464.         LOG("Multiple Item Package: Item: \"" + fileURL.fileName + "\" does " +
  4465.             "not contain a valid package to install.");
  4466.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4467.         showMessage("missingPackageFilesTitle",
  4468.                     [bundle.GetStringFromName("type-" + installData.type)],
  4469.                     "missingPackageFilesMessage", [installData.name,
  4470.                     bundle.GetStringFromName("type-" + installData.type)]);
  4471.         return;
  4472.       }
  4473.  
  4474.       for (i = 0; i < files.length; ++i) {
  4475.         em.installItemFromFileInternal(files[i], aInstallLocationKey, null);
  4476.         files[i].remove(false);
  4477.       }
  4478.     }
  4479.  
  4480.     /**
  4481.      * An observer for the Extension Update System.
  4482.      * @constructor
  4483.      */
  4484.     function IncompatibleObserver() {}
  4485.     IncompatibleObserver.prototype = {
  4486.       _xpi: null,
  4487.       _installManifest: null,
  4488.  
  4489.       /**
  4490.        * Ask the Extension Update System if there are any version updates for
  4491.        * this item that will allow it to be compatible with this version of
  4492.        * the Application.
  4493.        * @param   item
  4494.        *          An nsIUpdateItem representing the item being installed.
  4495.        * @param   installManifest
  4496.        *          The Install Manifest datasource for the item.
  4497.        * @param   xpiFile
  4498.        *          The staged source XPI file that contains the item. Cleaned
  4499.        *          up by this process.
  4500.        * @param   installRDF
  4501.        *          The install.rdf file that was extracted from the xpi.
  4502.        */
  4503.       checkForUpdates: function(item, installManifest, xpiFile) {
  4504.         this._xpi             = xpiFile;
  4505.         this._installManifest = installManifest;
  4506.  
  4507.         for (var i = 0; i < em._installListeners.length; ++i)
  4508.           em._installListeners[i].onCompatibilityCheckStarted(item);
  4509.         em._compatibilityCheckCount++;
  4510.         em.update([item], 1, Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY, this);
  4511.       },
  4512.  
  4513.       /**
  4514.        * See nsIExtensionManager.idl
  4515.        */
  4516.       onUpdateStarted: function() {
  4517.         LOG("Phone Home Listener: Update Started");
  4518.       },
  4519.  
  4520.       /**
  4521.        * See nsIExtensionManager.idl
  4522.        */
  4523.       onUpdateEnded: function() {
  4524.         LOG("Phone Home Listener: Update Ended");
  4525.       },
  4526.  
  4527.       /**
  4528.        * See nsIExtensionManager.idl
  4529.        */
  4530.       onAddonUpdateStarted: function(addon) {
  4531.         if (!addon)
  4532.           throw Cr.NS_ERROR_INVALID_ARG;
  4533.  
  4534.         LOG("Phone Home Listener: Update For " + addon.id + " started");
  4535.         em.datasource.addIncompatibleUpdateItem(addon.name, this._xpi.path,
  4536.                                                 addon.type, addon.version);
  4537.       },
  4538.  
  4539.       /**
  4540.        * See nsIExtensionManager.idl
  4541.        */
  4542.       onAddonUpdateEnded: function(addon, status) {
  4543.         if (!addon)
  4544.           throw Cr.NS_ERROR_INVALID_ARG;
  4545.  
  4546.         LOG("Phone Home Listener: Update For " + addon.id + " ended, status = " + status);
  4547.         em.datasource.removeDownload(this._xpi.path);
  4548.         LOG("Version Check Phone Home Completed");
  4549.  
  4550.         for (var i = 0; i < em._installListeners.length; ++i)
  4551.           em._installListeners[i].onCompatibilityCheckEnded(addon, status);
  4552.  
  4553.         // Only compatibility updates (e.g. STATUS_VERSIONINFO) are currently
  4554.         // supported
  4555.         if (status == Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO) {
  4556.           em.datasource.setTargetApplicationInfo(addon.id,
  4557.                                                  addon.targetAppID,
  4558.                                                  addon.minAppVersion,
  4559.                                                  addon.maxAppVersion,
  4560.                                                  this._installManifest);
  4561.  
  4562.           // Try and install again, but use the updated compatibility DB.
  4563.           // This will send out an apropriate onInstallEnded notification for us.
  4564.           em.installItemFromFileInternal(this._xpi, aInstallLocationKey,
  4565.                                          this._installManifest);
  4566.  
  4567.           // Add the updated compatibility info to the datasource if done
  4568.           if (StartupCache.entries[aInstallLocationKey][addon.id].op == OP_NONE) {
  4569.             em.datasource.setTargetApplicationInfo(addon.id,
  4570.                                                    addon.targetAppID,
  4571.                                                    addon.minAppVersion,
  4572.                                                    addon.maxAppVersion,
  4573.                                                    null);
  4574.           }
  4575.           else { // needs a restart
  4576.             // Add updatedMinVersion and updatedMaxVersion so it can be used
  4577.             // to update the datasource during the installation or upgrade.
  4578.             em.datasource.setUpdatedTargetAppInfo(addon.id,
  4579.                                                   addon.targetAppID,
  4580.                                                   addon.minAppVersion,
  4581.                                                   addon.maxAppVersion,
  4582.                                                   null);
  4583.           }
  4584.         }
  4585.         else {
  4586.           em.datasource.removeDownload(this._xpi.path);
  4587.           showIncompatibleError(installData);
  4588.           LOG("Add-on " + addon.id + " is incompatible with " +
  4589.               BundleManager.appName + " " + gApp.version + ", Toolkit " +
  4590.               gApp.platformVersion + ". Remote compatibility check did not " +
  4591.               "resolve this.");
  4592.           
  4593.           for (var i = 0; i < em._installListeners.length; ++i)
  4594.             em._installListeners[i].onInstallEnded(addon, INSTALLERROR_INCOMPATIBLE_VERSION);
  4595.  
  4596.           // We are responsible for cleaning up this file!
  4597.           InstallLocations.get(aInstallLocationKey).removeFile(this._xpi);
  4598.         }
  4599.  
  4600.         em._compatibilityCheckCount--;
  4601.         // If there are no more compatibility checks running and no downloads in
  4602.         // progress then the install operations are complete.
  4603.         if (em._compatibilityCheckCount == 0 && em._transactions.length == 0) {
  4604.           for (var i = 0; i < em._installListeners.length; ++i)
  4605.             em._installListeners[i].onInstallsCompleted();
  4606.         }
  4607.       },
  4608.  
  4609.       QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonUpdateCheckListener])
  4610.     }
  4611.  
  4612.     var shouldPhoneHomeIfNecessary = false;
  4613.     if (!aInstallManifest) {
  4614.       // If we were not called with an Install Manifest, we were called from
  4615.       // some other path than the Phone Home system, so we do want to phone
  4616.       // home if the version is incompatible. As this is the first point in the
  4617.       // install process we must notify observers here.
  4618.  
  4619.       var addon = makeItem(getURIFromFile(aXPIFile).spec, "",
  4620.                            aInstallLocationKey, "", "", "",
  4621.                            getURIFromFile(aXPIFile).spec,
  4622.                            "", "", "", "", 0, gApp.id);
  4623.       for (var i = 0; i < this._installListeners.length; ++i)
  4624.         this._installListeners[i].onInstallStarted(addon);
  4625.  
  4626.       shouldPhoneHomeIfNecessary = true;
  4627.       var installManifest = null;
  4628.       var installManifestFile = extractRDFFileToTempDir(aXPIFile,
  4629.                                                         FILE_INSTALL_MANIFEST,
  4630.                                                         true);
  4631.       if (installManifestFile.exists()) {
  4632.         installManifest = getInstallManifest(installManifestFile);
  4633.         installManifestFile.remove(false);
  4634.       }
  4635.       if (!installManifest) {
  4636.         LOG("The Install Manifest supplied by this item is not well-formed. " +
  4637.             "Installation will not proceed.");
  4638.         for (var i = 0; i < this._installListeners.length; ++i)
  4639.           this._installListeners[i].onInstallEnded(addon, INSTALLERROR_INVALID_MANIFEST);
  4640.         return;
  4641.       }
  4642.     }
  4643.     else
  4644.       installManifest = aInstallManifest;
  4645.  
  4646.     var installData = this._getInstallData(installManifest);
  4647.     // Recreate the add-on item with the full detail from the install manifest
  4648.     addon = makeItem(installData.id, installData.version,
  4649.                      aInstallLocationKey,
  4650.                      installData.currentApp ? installData.currentApp.minVersion : "",
  4651.                      installData.currentApp ? installData.currentApp.maxVersion : "",
  4652.                      installData.name,
  4653.                      getURIFromFile(aXPIFile).spec,
  4654.                      "", /* XPI Update Hash */
  4655.                      "", /* Icon URL */
  4656.                      installData.updateURL || "",
  4657.                      installData.updateKey || "",
  4658.                      installData.type,
  4659.                      installData.currentApp ? installData.currentApp.id : "");
  4660.  
  4661.     switch (installData.error) {
  4662.     case INSTALLERROR_INCOMPATIBLE_VERSION:
  4663.       // Since the caller cleans up |aXPIFile|, and we're not yet sure whether or
  4664.       // not we need it (we may need it if a remote version bump that makes it
  4665.       // compatible is discovered by the call home) - so we must stage it for
  4666.       // later ourselves.
  4667.       if (shouldPhoneHomeIfNecessary && installData.currentApp) {
  4668.         var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4669.         if (!installLocation)
  4670.           return;
  4671.         var stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4672.         (new IncompatibleObserver(this)).checkForUpdates(addon, installManifest,
  4673.                                                          stagedFile);
  4674.         // Return early to prevent deletion of the install manifest file.
  4675.         return;
  4676.       }
  4677.       else {
  4678.         // XXXben Look up XULRunnerSettingsThingy to see if there is a registered
  4679.         //        app that can handle this item, if so just stage and don't show
  4680.         //        this error!
  4681.         showIncompatibleError(installData);
  4682.         LOG("Add-on " + installData.id + " is incompatible with " +
  4683.             BundleManager.appName + " " + gApp.version + ", Toolkit " +
  4684.             gApp.platformVersion + ". Remote compatibility check was not performed.");
  4685.       }
  4686.       break;
  4687.     case INSTALLERROR_SUCCESS:
  4688.       // Installation of multiple extensions / themes contained within a single xpi.
  4689.       if (installData.type == Ci.nsIUpdateItem.TYPE_MULTI_XPI) {
  4690.         installMultiXPI(aXPIFile, installData);
  4691.         break;
  4692.       }
  4693.  
  4694.       // Stage the extension's XPI so it can be extracted at the next restart.
  4695.       var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4696.       if (!installLocation) {
  4697.         // No cleanup of any of the staged XPI files should be required here,
  4698.         // because this should only ever fail on the first recurse through
  4699.         // this function, BEFORE staging takes place... technically speaking
  4700.         // a location could become readonly during the phone home process,
  4701.         // but that's an edge case I don't care about.
  4702.         for (var i = 0; i < this._installListeners.length; ++i)
  4703.           this._installListeners[i].onInstallEnded(addon, INSTALLERROR_RESTRICTED);
  4704.         return;
  4705.       }
  4706.  
  4707.       // Stage a copy of the XPI/JAR file for our own evil purposes...
  4708.       stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4709.  
  4710.       var restartRequired = this.installRequiresRestart(installData.id,
  4711.                                                         installData.type);
  4712.       // Determine which configuration function to use based on whether or not
  4713.       // there is data about this item in our datasource already - if there is
  4714.       // we want to upgrade, otherwise we install fresh.
  4715.       var ds = this.datasource;
  4716.       if (installData.id in ds.visibleItems && ds.visibleItems[installData.id]) {
  4717.         // We enter this function if any data corresponding to an existing GUID
  4718.         // is found, regardless of its Install Location. We need to check before
  4719.         // "upgrading" an item that Install Location of the new item is of equal
  4720.         // or higher priority than the old item, to make sure the datasource only
  4721.         // ever tracks metadata for active items.
  4722.         var oldInstallLocation = this.getInstallLocation(installData.id);
  4723.         if (oldInstallLocation.priority >= installLocation.priority) {
  4724.           this._upgradeItem(installManifest, installData.id, installLocation,
  4725.                             installData.type);
  4726.           if (!restartRequired) {
  4727.             this._finalizeUpgrade(installData.id, installLocation);
  4728.             this._finalizeInstall(installData.id, stagedFile);
  4729.           }
  4730.         }
  4731.       }
  4732.       else {
  4733.         this._configureForthcomingItem(installManifest, installData.id,
  4734.                                         installLocation, installData.type);
  4735.         if (!restartRequired) {
  4736.           this._finalizeInstall(installData.id, stagedFile);
  4737.           if (installData.type == Ci.nsIUpdateItem.TYPE_THEME) {
  4738.             var internalName = this.datasource.getItemProperty(installData.id, "internalName");
  4739.             if (gPref.getBoolPref(PREF_EM_DSS_ENABLED)) {
  4740.               gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, internalName);
  4741.             }
  4742.             else {
  4743.               gPref.setBoolPref(PREF_DSS_SWITCHPENDING, true);
  4744.               gPref.setCharPref(PREF_DSS_SKIN_TO_SELECT, internalName);
  4745.             }
  4746.           }
  4747.         }
  4748.       }
  4749.       this._updateManifests(restartRequired);
  4750.       break;
  4751.     case INSTALLERROR_INVALID_GUID:
  4752.       LOG("Invalid GUID: Item has GUID: \"" + installData.id + "\"" +
  4753.           " which is not well-formed.");
  4754.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4755.       showMessage("incompatibleTitle",
  4756.                   [bundle.GetStringFromName("type-" + installData.type)],
  4757.                   "invalidGUIDMessage", [installData.name, installData.id]);
  4758.       break;
  4759.     case INSTALLERROR_INVALID_VERSION:
  4760.       LOG("Invalid Version: Item: \"" + installData.id + "\" has version " +
  4761.           installData.version + " which is not well-formed.");
  4762.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4763.       showMessage("incompatibleTitle",
  4764.                   [bundle.GetStringFromName("type-" + installData.type)],
  4765.                   "invalidVersionMessage", [installData.name, installData.version]);
  4766.       break;
  4767.     case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  4768.       const osABI = gOSTarget + "_" + gXPCOMABI;
  4769.       LOG("Incompatible Platform: Item: \"" + installData.id + "\" is not " +
  4770.           "compatible with '" + osABI + "'.");
  4771.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4772.       showMessage("incompatibleTitle",
  4773.                   [bundle.GetStringFromName("type-" + installData.type)],
  4774.                   "incompatiblePlatformMessage",
  4775.                   [installData.name, BundleManager.appName, osABI]);
  4776.       break;
  4777.     case INSTALLERROR_BLOCKLISTED:
  4778.       LOG("Blocklisted Item: Item: \"" + installData.id + "\" version " +
  4779.           installData.version + " was not installed.");
  4780.       showBlocklistMessage([installData], true);
  4781.       break;
  4782.     case INSTALLERROR_INSECURE_UPDATE:
  4783.       LOG("No secure updates: Item: \"" + installData.id + "\" version " + 
  4784.           installData.version + " was not installed.");
  4785.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4786.       showMessage("incompatibleTitle", 
  4787.                   [bundle.GetStringFromName("type-" + installData.type)], 
  4788.                   "insecureUpdateMessage", [installData.name]);
  4789.       break;
  4790.     default:
  4791.       break;
  4792.     }
  4793.  
  4794.     // Check to see if this item supports other applications and in that case
  4795.     // stage the the XPI file in the location specified by those applications.
  4796.     stageXPIForOtherApps(aXPIFile, installData);
  4797.  
  4798.     // The install of this item is complete, notify observers
  4799.     for (var i = 0; i < this._installListeners.length; ++i)
  4800.       this._installListeners[i].onInstallEnded(addon, installData.error);
  4801.   },
  4802.  
  4803.   /**
  4804.    * Whether or not this type's installation/uninstallation requires
  4805.    * the application to be restarted.
  4806.    * @param   id
  4807.    *          The GUID of the item
  4808.    * @param   type
  4809.    *          The nsIUpdateItem type of the item
  4810.    * @returns true if installation of an item of this type requires a
  4811.    *          restart.
  4812.    */
  4813.   installRequiresRestart: function(id, type) {
  4814.     switch (type) {
  4815.     case Ci.nsIUpdateItem.TYPE_THEME:
  4816.       var internalName = this.datasource.getItemProperty(id, "internalName");
  4817.       var needsRestart = false;
  4818.       if (gPref.prefHasUserValue(PREF_DSS_SKIN_TO_SELECT))
  4819.         needsRestart = internalName == gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  4820.       if (!needsRestart &&
  4821.           gPref.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN))
  4822.         needsRestart = internalName == gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  4823.       return needsRestart;
  4824.     }
  4825.     return ((type & Ci.nsIUpdateItem.TYPE_ADDON) > 0);
  4826.   },
  4827.  
  4828.   /**
  4829.    * Perform initial configuration on an item that has just or will be
  4830.    * installed. This inserts the item into the appropriate container in the
  4831.    * datasource, so that the application UI shows the item even if it will
  4832.    * not actually be installed until the next restart.
  4833.    * @param   installManifest
  4834.    *          The Install Manifest datasource that describes this item.
  4835.    * @param   id
  4836.    *          The GUID of this item.
  4837.    * @param   installLocation
  4838.    *          The Install Location where this item is installed.
  4839.    * @param   type
  4840.    *          The nsIUpdateItem type of this item.
  4841.    */
  4842.   _configureForthcomingItem: function(installManifest, id, installLocation, type) {
  4843.     var ds = this.datasource;
  4844.     ds.updateVisibleList(id, installLocation.name, false);
  4845.  
  4846.     var name = null;
  4847.     var localized = findClosestLocalizedResource(installManifest, gInstallManifestRoot);
  4848.     if (localized)
  4849.       name = installManifest.GetTarget(localized, EM_R("name"), true);
  4850.     else
  4851.       name = EM_L(getManifestProperty(installManifest, "name"));
  4852.  
  4853.     var props = { name            : name,
  4854.                   version         : EM_L(getManifestProperty(installManifest, "version")),
  4855.                   newVersion      : EM_L(getManifestProperty(installManifest, "version")),
  4856.                   installLocation : EM_L(installLocation.name),
  4857.                   type            : EM_I(type),
  4858.                   availableUpdateURL    : null,
  4859.                   availableUpdateHash   : null,
  4860.                   availableUpdateVersion: null,
  4861.                   availableUpdateInfo   : null };
  4862.     ds.setItemProperties(id, props);
  4863.     ds.updateProperty(id, "availableUpdateURL");
  4864.  
  4865.     this._setOp(id, OP_NEEDS_INSTALL);
  4866.  
  4867.     // Insert it into the child list NOW rather than later because:
  4868.     // - extensions installed using the command line need to be a member
  4869.     //   of a container during the install phase for the code to be able
  4870.     //   to identify profile vs. global
  4871.     // - extensions installed through the UI should show some kind of
  4872.     //   feedback to indicate their presence is forthcoming (i.e. they
  4873.     //   will be available after a restart).
  4874.     ds.insertItemIntoContainer(id);
  4875.  
  4876.     this._notifyAction(id, EM_ITEM_INSTALLED);
  4877.   },
  4878.  
  4879.   /**
  4880.    * Perform configuration on an item that has just or will be upgraded.
  4881.    * @param   installManifest
  4882.    *          The Install Manifest datasource that describes this item.
  4883.    * @param   itemID
  4884.    *          The GUID of this item.
  4885.    * @param   installLocation
  4886.    *          The Install Location where this item is installed.
  4887.    * @param   type
  4888.    *          The nsIUpdateItem type of this item.
  4889.    */
  4890.   _upgradeItem: function (installManifest, id, installLocation, type) {
  4891.     // Don't change any props that would need to be reset if the install fails.
  4892.     // They will be reset as appropriate by the upgrade/install process.
  4893.     var ds = this.datasource;
  4894.     ds.updateVisibleList(id, installLocation.name, false);
  4895.     var props = { installLocation : EM_L(installLocation.name),
  4896.                   type            : EM_I(type),
  4897.                   newVersion      : EM_L(getManifestProperty(installManifest, "version")),
  4898.                   availableUpdateURL      : null,
  4899.                   availableUpdateHash     : null,
  4900.                   availableUpdateVersion  : null,
  4901.                   availableUpdateInfo     : null };
  4902.     ds.setItemProperties(id, props);
  4903.     ds.updateProperty(id, "availableUpdateURL");
  4904.  
  4905.     this._setOp(id, OP_NEEDS_UPGRADE);
  4906.     this._notifyAction(id, EM_ITEM_UPGRADED);
  4907.   },
  4908.  
  4909.   /**
  4910.    * Completes an Extension's installation.
  4911.    * @param   id
  4912.    *          The GUID of the Extension to install.
  4913.    * @param   file
  4914.    *          The XPI/JAR file to install from. If this is null, we try to
  4915.    *          determine the stage file location from the ID.
  4916.    */
  4917.   _finalizeInstall: function(id, file) {
  4918.     var ds = this.datasource;
  4919.     var type = ds.getItemProperty(id, "type");
  4920.     if (id == 0 || id == -1) {
  4921.       ds.removeCorruptItem(id);
  4922.       return;
  4923.     }
  4924.     var installLocation = this.getInstallLocation(id);
  4925.     if (!installLocation) {
  4926.       // If the install location is null, that means we've reached the finalize
  4927.       // state without the item ever having metadata added for it, which implies
  4928.       // bogus data in the Startup Cache. Clear the entries and don't do anything
  4929.       // else.
  4930.       var entries = StartupCache.findEntries(id);
  4931.       for (var i = 0; i < entries.length; ++i) {
  4932.         var location = InstallLocations.get(entries[i].location);
  4933.         StartupCache.clearEntry(location, id);
  4934.         PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4935.       }
  4936.       return;
  4937.     }
  4938.     var itemLocation = installLocation.getItemLocation(id);
  4939.  
  4940.     if (!file && "stageFile" in installLocation)
  4941.       file = installLocation.getStageFile(id);
  4942.  
  4943.     // If |file| is null or does not exist, the installer assumes the item is
  4944.     // a dropped-in directory.
  4945.     var installer = new Installer(this.datasource, id, installLocation, type);
  4946.     installer.installFromFile(file);
  4947.  
  4948.     // If the file was staged, we must clean it up ourselves, otherwise the
  4949.     // EM caller is responsible for doing so (e.g. XPInstall)
  4950.     if (file)
  4951.       installLocation.removeFile(file);
  4952.  
  4953.     // Clear the op flag from the Startup Cache and Pending Operations sets
  4954.     StartupCache.put(installLocation, id, OP_NONE, true);
  4955.     PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4956.   },
  4957.  
  4958.   /**
  4959.    * Removes an item's metadata in preparation for an upgrade-install.
  4960.    * @param   id
  4961.    *          The GUID of the item to uninstall.
  4962.    * @param   installLocation
  4963.    *          The nsIInstallLocation of the item
  4964.    */
  4965.   _finalizeUpgrade: function(id, installLocation) {
  4966.     // Retrieve the item properties *BEFORE* we clean the resource!
  4967.     var ds = this.datasource;
  4968.  
  4969.     var stagedFile = null;
  4970.     if ("getStageFile" in installLocation)
  4971.       stagedFile = installLocation.getStageFile(id);
  4972.  
  4973.     if (stagedFile)
  4974.       var installRDF = extractRDFFileToTempDir(stagedFile, FILE_INSTALL_MANIFEST, true);
  4975.     else
  4976.       installRDF = installLocation.getItemFile(id, FILE_INSTALL_MANIFEST);
  4977.     if (installRDF.exists()) {
  4978.       var installManifest = getInstallManifest(installRDF);
  4979.       if (installManifest) {
  4980.         var type = getAddonTypeFromInstallManifest(installManifest);
  4981.         var userDisabled = ds.getItemProperty(id, "userDisabled") == "true";
  4982.  
  4983.         // Clean the item resource
  4984.         ds.removeItemMetadata(id);
  4985.         // Now set up the properties on the item to mimic an item in its
  4986.         // "initial state" for installation.
  4987.         this._configureForthcomingItem(installManifest, id, installLocation,
  4988.                                        type);
  4989.         if (userDisabled)
  4990.           ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  4991.       }
  4992.       if (stagedFile)
  4993.         installRDF.remove(false);
  4994.     }
  4995.     // Clear the op flag from the Pending Operations set. Do NOT clear op flag in
  4996.     // the startup cache since this may have been reset to OP_NEEDS_INSTALL by
  4997.     // |_configureForthcomingItem|.
  4998.     PendingOperations.clearItem(OP_NEEDS_UPGRADE, id);
  4999.   },
  5000.  
  5001.   /**
  5002.    * Completes an item's uninstallation.
  5003.    * @param   id
  5004.    *          The GUID of the item to uninstall.
  5005.    */
  5006.   _finalizeUninstall: function(id) {
  5007.     var ds = this.datasource;
  5008.  
  5009.     var installLocation = this.getInstallLocation(id);
  5010.     if (!installLocation.itemIsManagedIndependently(id)) {
  5011.       try {
  5012.         // Having a callback that does nothing just causes the directory to be
  5013.         // removed.
  5014.         safeInstallOperation(id, installLocation,
  5015.                              { data: null, callback: function() { } });
  5016.       }
  5017.       catch (e) {
  5018.         ERROR("_finalizeUninstall: failed to remove directory for item: " + id +
  5019.               " at Install Location: " + installLocation.name + ", rolling back uninstall");
  5020.         var manifest = installLocation.getItemFile(id, "FILE_INSTALL_MANIFEST");
  5021.         // If there is no manifest then either the rollback failed, or there was
  5022.         // no manifest in the first place. Either way this item is now invalid
  5023.         // and we shouldn't try to re-install it.
  5024.         if (manifest.exists()) {
  5025.           // Removal of the files failed, reset the uninstalled flag and rewrite
  5026.           // the install manifests so this item's components are registered.
  5027.           // Clear the op flag from the Startup Cache
  5028.           StartupCache.put(installLocation, id, OP_NONE, true);
  5029.           var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  5030.           this._updateManifests(restartRequired);
  5031.           return;
  5032.         }
  5033.       }
  5034.     }
  5035.     else if (installLocation.name == KEY_APP_PROFILE ||
  5036.              installLocation.name == KEY_APP_GLOBAL ||
  5037.              installLocation.name == KEY_APP_SYSTEM_USER) {
  5038.       // Check for a pointer file and remove it if it exists
  5039.       var pointerFile = installLocation.location.clone();
  5040.       pointerFile.append(id);
  5041.       if (pointerFile.exists() && !pointerFile.isDirectory())
  5042.         pointerFile.remove(false);
  5043.     }
  5044.  
  5045.     // Clean the item resource
  5046.     ds.removeItemMetadata(id);
  5047.  
  5048.     // Do this LAST since inferences are made about an item based on
  5049.     // what container it's in.
  5050.     ds.removeItemFromContainer(id);
  5051.  
  5052.     // Clear the op flag from the Startup Cache and the Pending Operations set.
  5053.     StartupCache.clearEntry(installLocation, id);
  5054.     PendingOperations.clearItem(OP_NEEDS_UNINSTALL, id);
  5055.   },
  5056.  
  5057.   /**
  5058.    * Uninstalls an item. If the uninstallation cannot be performed immediately
  5059.    * it is scheduled for the next restart.
  5060.    * @param   id
  5061.    *          The GUID of the item to uninstall.
  5062.    */
  5063.   uninstallItem: function(id) {
  5064.     var ds = this.datasource;
  5065.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  5066.     if (!ds.isDownloadItem(id)) {
  5067.       var opType = ds.getItemProperty(id, "opType");
  5068.       var installLocation = this.getInstallLocation(id);
  5069.       // Removes any staged xpis for this item.
  5070.       if (opType == OP_NEEDS_UPGRADE || opType == OP_NEEDS_INSTALL) {
  5071.         var stageFile = installLocation.getStageFile(id);
  5072.         if (stageFile)
  5073.           installLocation.removeFile(stageFile);
  5074.       }
  5075.       // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  5076.       // and are removed immediately since the uninstall can't be canceled.
  5077.       if (opType == OP_NEEDS_INSTALL) {
  5078.         ds.removeItemMetadata(id);
  5079.         ds.removeItemFromContainer(id);
  5080.         ds.updateVisibleList(id, null, true);
  5081.         StartupCache.clearEntry(installLocation, id);
  5082.         this._updateManifests(false);
  5083.       }
  5084.       else {
  5085.         if (opType == OP_NEEDS_UPGRADE)
  5086.           ds.setItemProperty(id, "newVersion", null);
  5087.         this._setOp(id, OP_NEEDS_UNINSTALL);
  5088.         var type = ds.getItemProperty(id, "type");
  5089.         var restartRequired = this.installRequiresRestart(id, type);
  5090.         if (!restartRequired) {
  5091.           this._finalizeUninstall(id);
  5092.           this._updateManifests(restartRequired);
  5093.         }
  5094.       }
  5095.     }
  5096.     else {
  5097.       // Bad download entry - uri is url, e.g. "http://www.foo.com/test.xpi"
  5098.       // ... just remove it from the list.
  5099.       ds.removeCorruptDLItem(id);
  5100.     }
  5101.  
  5102.     this._notifyAction(id, EM_ITEM_UNINSTALLED);
  5103.   },
  5104.  
  5105.   /* See nsIExtensionManager.idl */
  5106.   cancelInstallItem: function(id) {
  5107.     var ds = this.datasource;
  5108.     var opType = ds.getItemProperty(id, "opType");
  5109.     if (opType != OP_NEEDS_UPGRADE && opType != OP_NEEDS_INSTALL)
  5110.       return;
  5111.  
  5112.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  5113.     var installLocation = this.getInstallLocation(id);
  5114.     // Removes any staged xpis for this item.
  5115.     var stageFile = installLocation.getStageFile(id);
  5116.     if (stageFile)
  5117.       installLocation.removeFile(stageFile);
  5118.     // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  5119.     // and just need to be removed completely from the ds.
  5120.     if (opType == OP_NEEDS_INSTALL) {
  5121.       ds.removeItemMetadata(id);
  5122.       ds.removeItemFromContainer(id);
  5123.       ds.updateVisibleList(id, null, true);
  5124.       StartupCache.clearEntry(installLocation, id);
  5125.       this._updateManifests(false);
  5126.       this._notifyAction(id, EM_ITEM_CANCEL);
  5127.     }
  5128.     else {
  5129.       // Clear upgrade information and reset any request to enable/disable.
  5130.       ds.setItemProperty(id, EM_R("newVersion"), null);
  5131.       var appDisabled = ds.getItemProperty(id, "appDisabled");
  5132.       var userDisabled = ds.getItemProperty(id, "userDisabled");
  5133.       if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  5134.         this._setOp(id, OP_NONE);
  5135.         this._notifyAction(id, EM_ITEM_CANCEL);
  5136.       }
  5137.       else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  5138.         this._setOp(id, OP_NEEDS_DISABLE);
  5139.         this._notifyAction(id, EM_ITEM_DISABLED);
  5140.       }
  5141.       else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  5142.         this._setOp(id, OP_NEEDS_ENABLE);
  5143.         this._notifyAction(id, EM_ITEM_ENABLED);
  5144.       }
  5145.       else {
  5146.         this._setOp(id, OP_NONE);
  5147.         this._notifyAction(id, EM_ITEM_CANCEL);
  5148.       }
  5149.     }
  5150.   },
  5151.  
  5152.   /**
  5153.    * Cancels a pending uninstall of an item
  5154.    * @param   id
  5155.    *          The ID of the item.
  5156.    */
  5157.   cancelUninstallItem: function(id) {
  5158.     var ds = this.datasource;
  5159.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5160.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5161.     if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  5162.       this._setOp(id, OP_NONE);
  5163.       this._notifyAction(id, EM_ITEM_CANCEL);
  5164.     }
  5165.     else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  5166.       this._setOp(id, OP_NEEDS_DISABLE);
  5167.       this._notifyAction(id, EM_ITEM_DISABLED);
  5168.     }
  5169.     else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  5170.       this._setOp(id, OP_NEEDS_ENABLE);
  5171.       this._notifyAction(id, EM_ITEM_ENABLED);
  5172.     }
  5173.     else {
  5174.       this._setOp(id, OP_NONE);
  5175.       this._notifyAction(id, EM_ITEM_CANCEL);
  5176.     }
  5177.   },
  5178.  
  5179.   /**
  5180.    * Sets the pending operation for a visible item.
  5181.    * @param   id
  5182.    *          The GUID of the item
  5183.    * @param   op
  5184.    *          The name of the operation to be performed
  5185.    */
  5186.   _setOp: function(id, op) {
  5187.     var location = this.getInstallLocation(id);
  5188.     StartupCache.put(location, id, op, true);
  5189.     PendingOperations.addItem(op, { locationKey: location.name, id: id });
  5190.     var ds = this.datasource;
  5191.     if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE)
  5192.       ds.updateDownloadState(PREFIX_ITEM_URI + id, "success");
  5193.  
  5194.     ds.updateProperty(id, "opType");
  5195.     ds.updateProperty(id, "updateable");
  5196.     ds.updateProperty(id, "satisfiesDependencies");
  5197.     var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  5198.     this._updateDependentItemsForID(id);
  5199.     this._updateManifests(restartRequired);
  5200.   },
  5201.  
  5202.   /**
  5203.    * Note on appDisabled and userDisabled property arcs.
  5204.    * The appDisabled and userDisabled RDF property arcs are used to store
  5205.    * the pending operation for app disabling and user disabling for an item as
  5206.    * well as the user and app disabled status after the pending operation has
  5207.    * been completed upon restart. When the appDisabled value changes the value
  5208.    * of userDisabled is reset to prevent the state of widgets and status
  5209.    * messages from being in an incorrect state.
  5210.    */
  5211.  
  5212.   /**
  5213.    * Enables an item for the application (e.g. the item satisfies all
  5214.    * requirements like app compatibility for it to be enabled). The appDisabled
  5215.    * property arc will be removed if the item will be app disabled on next
  5216.    * restart to cancel the app disabled operation for the item otherwise the
  5217.    * property value will be set to OP_NEEDS_ENABLE. The item's pending
  5218.    * operations are then evaluated in order to set the operation to perform
  5219.    * and notify the observers if the operation has been changed.
  5220.    * See "Note on appDisabled and userDisabled property arcs" above.
  5221.    * @param   id
  5222.    *          The ID of the item to be enabled by the application.
  5223.    */
  5224.   _appEnableItem: function(id) {
  5225.     var ds = this.datasource;
  5226.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5227.     if (appDisabled == OP_NONE || appDisabled == OP_NEEDS_ENABLE)
  5228.       return;
  5229.  
  5230.     var opType = ds.getItemProperty(id, "opType");
  5231.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5232.     // reset user disabled if it has a pending operation to prevent the ui
  5233.     // state from getting confused as to an item's current state.
  5234.     if (userDisabled == OP_NEEDS_DISABLE)
  5235.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5236.     else if (userDisabled == OP_NEEDS_ENABLE)
  5237.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5238.  
  5239.     if (appDisabled == OP_NEEDS_DISABLE)
  5240.       ds.setItemProperty(id, EM_R("appDisabled"), null);
  5241.     else if (appDisabled == "true")
  5242.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_ENABLE));
  5243.  
  5244.     // Don't set a new operation when there is a pending uninstall operation.
  5245.     if (opType == OP_NEEDS_UNINSTALL) {
  5246.       this._updateDependentItemsForID(id);
  5247.       return;
  5248.     }
  5249.  
  5250.     var operation, action;
  5251.     // if this item is already enabled or user disabled don't set a pending
  5252.     // operation - instead immediately enable it and reset the operation type
  5253.     // if needed.
  5254.     if (appDisabled == OP_NEEDS_DISABLE || appDisabled == OP_NONE ||
  5255.         userDisabled == "true") {
  5256.       if (opType != OP_NONE) {
  5257.         operation = OP_NONE;
  5258.         action = EM_ITEM_CANCEL;
  5259.       }
  5260.     }
  5261.     else {
  5262.       if (opType != OP_NEEDS_ENABLE) {
  5263.         operation = OP_NEEDS_ENABLE;
  5264.         action = EM_ITEM_ENABLED;
  5265.       }
  5266.     }
  5267.  
  5268.     if (action) {
  5269.       this._setOp(id, operation);
  5270.       this._notifyAction(id, action);
  5271.     }
  5272.     else {
  5273.       ds.updateProperty(id, "satisfiesDependencies");
  5274.       this._updateDependentItemsForID(id);
  5275.     }
  5276.   },
  5277.  
  5278.   /**
  5279.    * Disables an item for the application (e.g. the item doesn't satisfy all
  5280.    * requirements like app compatibility for it to be enabled). The appDisabled
  5281.    * property arc will be set to true if the item will be app enabled on next
  5282.    * restart to cancel the app enabled operation for the item otherwise the
  5283.    * property value will be set to OP_NEEDS_DISABLE. The item's pending
  5284.    * operations are then evaluated in order to set the operation to perform
  5285.    * and notify the observers if the operation has been changed.
  5286.    * See "Note on appDisabled and userDisabled property arcs" above.
  5287.    * @param   id
  5288.    *          The ID of the item to be disabled by the application.
  5289.    */
  5290.   _appDisableItem: function(id) {
  5291.     var ds = this.datasource;
  5292.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5293.     if (appDisabled == "true" || appDisabled == OP_NEEDS_DISABLE)
  5294.       return;
  5295.  
  5296.     var opType = ds.getItemProperty(id, "opType");
  5297.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5298.  
  5299.     // reset user disabled if it has a pending operation to prevent the ui
  5300.     // state from getting confused as to an item's current state.
  5301.     if (userDisabled == OP_NEEDS_DISABLE)
  5302.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5303.     else if (userDisabled == OP_NEEDS_ENABLE)
  5304.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5305.  
  5306.     if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE ||
  5307.         ds.getItemProperty(id, "userDisabled") == "true")
  5308.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  5309.     else if (appDisabled == OP_NONE)
  5310.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_DISABLE));
  5311.  
  5312.     // Don't set a new operation when there is a pending uninstall operation.
  5313.     if (opType == OP_NEEDS_UNINSTALL) {
  5314.       this._updateDependentItemsForID(id);
  5315.       return;
  5316.     }
  5317.  
  5318.     var operation, action;
  5319.     // if this item is already disabled don't set a pending operation - instead
  5320.     // immediately disable it and reset the operation type if needed.
  5321.     if (appDisabled == OP_NEEDS_ENABLE || appDisabled == "true" ||
  5322.         userDisabled == OP_NEEDS_ENABLE || userDisabled == "true") {
  5323.       if (opType != OP_NONE) {
  5324.         operation = OP_NONE;
  5325.         action = EM_ITEM_CANCEL;
  5326.       }
  5327.     }
  5328.     else {
  5329.       if (opType != OP_NEEDS_DISABLE) {
  5330.         operation = OP_NEEDS_DISABLE;
  5331.         action = EM_ITEM_DISABLED;
  5332.       }
  5333.     }
  5334.  
  5335.     if (action) {
  5336.       this._setOp(id, operation);
  5337.       this._notifyAction(id, action);
  5338.     }
  5339.     else {
  5340.       ds.updateProperty(id, "satisfiesDependencies");
  5341.       this._updateDependentItemsForID(id);
  5342.     }
  5343.   },
  5344.  
  5345.   /**
  5346.    * Sets an item to be enabled by the user. If the item is already enabled this
  5347.    * clears the needs-enable operation for the next restart.
  5348.    * See "Note on appDisabled and userDisabled property arcs" above.
  5349.    * @param   id
  5350.    *          The ID of the item to be enabled by the user.
  5351.    */
  5352.   enableItem: function(id) {
  5353.     var ds = this.datasource;
  5354.     var opType = ds.getItemProperty(id, "opType");
  5355.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5356.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5357.  
  5358.     var operation, action;
  5359.     // if this item is already enabled don't set a pending operation - instead
  5360.     // immediately enable it and reset the operation type if needed.
  5361.     if (appDisabled == OP_NONE &&
  5362.         userDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NONE) {
  5363.       if (userDisabled == OP_NEEDS_DISABLE)
  5364.         ds.setItemProperty(id, EM_R("userDisabled"), null);
  5365.       if (opType != OP_NONE) {
  5366.         operation = OP_NONE;
  5367.         action = EM_ITEM_CANCEL;
  5368.       }
  5369.     }
  5370.     else {
  5371.       if (userDisabled == "true")
  5372.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_ENABLE));
  5373.       if (opType != OP_NEEDS_ENABLE) {
  5374.         operation = OP_NEEDS_ENABLE;
  5375.         action = EM_ITEM_ENABLED;
  5376.       }
  5377.     }
  5378.  
  5379.     if (action) {
  5380.       this._setOp(id, operation);
  5381.       this._notifyAction(id, action);
  5382.     }
  5383.     else {
  5384.       ds.updateProperty(id, "satisfiesDependencies");
  5385.       this._updateDependentItemsForID(id);
  5386.     }
  5387.   },
  5388.  
  5389.   /**
  5390.    * Sets an item to be disabled by the user. If the item is already disabled
  5391.    * this clears the needs-disable operation for the next restart.
  5392.    * See "Note on appDisabled and userDisabled property arcs" above.
  5393.    * @param   id
  5394.    *          The ID of the item to be disabled by the user.
  5395.    */
  5396.   disableItem: function(id) {
  5397.     var ds = this.datasource;
  5398.     var opType = ds.getItemProperty(id, "opType");
  5399.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5400.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5401.  
  5402.     var operation, action;
  5403.     // if this item is already disabled don't set a pending operation - instead
  5404.     // immediately disable it and reset the operation type if needed.
  5405.     if (userDisabled == OP_NEEDS_ENABLE || userDisabled == "true" ||
  5406.         appDisabled == OP_NEEDS_ENABLE) {
  5407.       if (userDisabled != "true")
  5408.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5409.       if (opType != OP_NONE) {
  5410.         operation = OP_NONE;
  5411.         action = EM_ITEM_CANCEL;
  5412.       }
  5413.     }
  5414.     else {
  5415.       if (userDisabled == OP_NONE)
  5416.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_DISABLE));
  5417.       if (opType != OP_NEEDS_DISABLE) {
  5418.         operation = OP_NEEDS_DISABLE;
  5419.         action = EM_ITEM_DISABLED;
  5420.       }
  5421.     }
  5422.  
  5423.     if (action) {
  5424.       this._setOp(id, operation);
  5425.       this._notifyAction(id, action);
  5426.     }
  5427.     else {
  5428.       ds.updateProperty(id, "satisfiesDependencies");
  5429.       this._updateDependentItemsForID(id);
  5430.     }
  5431.   },
  5432.  
  5433.   /**
  5434.    * Determines whether an item should be disabled by the application.
  5435.    * @param   id
  5436.    *          The ID of the item to check
  5437.    */
  5438.   _isUsableItem: function(id) {
  5439.     var ds = this.datasource;
  5440.     /* If we're not compatibility checking or if the item is compatible
  5441.      * and if it isn't blocklisted and has all dependencies satisfied then
  5442.      * proceed to the security check */
  5443.     if ((!gCheckCompatibility || ds.getItemProperty(id, "compatible") == "true") &&
  5444.         ds.getItemProperty(id, "blocklisted") == "false" &&
  5445.         ds.getItemProperty(id, "satisfiesDependencies") == "true") {
  5446.  
  5447.       // appManaged items aren't updated so no need to check update security.
  5448.       if (ds.getItemProperty(id, "appManaged") == "true")
  5449.         return true;
  5450.  
  5451.       /* If we are not ignoring update security then check that the item has
  5452.        * a secure update mechanism */
  5453.       return (!gCheckUpdateSecurity ||
  5454.               ds.getItemProperty(id, "providesUpdatesSecurely") == "true");
  5455.     }
  5456.     return false;
  5457.   },
  5458.  
  5459.   /**
  5460.    * Sets an item's dependent items disabled state for the app based on whether
  5461.    * its dependencies are met and the item is compatible.
  5462.    * @param   id
  5463.    *          The ID of the item whose dependent items will be checked
  5464.    */
  5465.   _updateDependentItemsForID: function(id) {
  5466.     var ds = this.datasource;
  5467.     var dependentItems = this.getDependentItemListForID(id, true, { });
  5468.     for (var i = 0; i < dependentItems.length; ++i) {
  5469.       var dependentID = dependentItems[i].id;
  5470.       ds.updateProperty(dependentID, "satisfiesDependencies");
  5471.       if (this._isUsableItem(dependentID))
  5472.         this._appEnableItem(dependentID);
  5473.       else
  5474.         this._appDisableItem(dependentID);
  5475.     }
  5476.   },
  5477.  
  5478.   /**
  5479.    * Notify observers of a change to an item that has been requested by the
  5480.    * user.
  5481.    */
  5482.   _notifyAction: function(id, reason) {
  5483.     gOS.notifyObservers(this.datasource.getItemForID(id),
  5484.                         EM_ACTION_REQUESTED_TOPIC, reason);
  5485.   },
  5486.  
  5487.   /**
  5488.    * See nsIExtensionManager.idl
  5489.    */
  5490.   update: function(items, itemCount, updateCheckType, listener) {
  5491.     for (i = 0; i < itemCount; ++i) {
  5492.       var currItem = items[i];
  5493.       if (!currItem)
  5494.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5495.     }
  5496.  
  5497.     if (items.length == 0)
  5498.       items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  5499.  
  5500.     var updater = new ExtensionItemUpdater(this);
  5501.     updater.checkForUpdates(items, items.length, updateCheckType, listener);
  5502.   },
  5503.  
  5504.  
  5505.   /**
  5506.    * Checks for changes to the blocklist using the local blocklist file,
  5507.    * application disables / enables items that have been added / removed from
  5508.    * the blocklist, and if there are additions to the blocklist this will
  5509.    * inform the user by displaying a list of the items added.
  5510.    *
  5511.    * XXXrstrong - this method is not terribly useful and was added so we can
  5512.    * trigger this check from the additional timer used by blocklisting.
  5513.    */
  5514.   checkForBlocklistChanges: function() {
  5515.     var ds = this.datasource;
  5516.     var items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  5517.     for (var i = 0; i < items.length; ++i) {
  5518.       var id = items[i].id;
  5519.       ds.updateProperty(id, "blocklisted");
  5520.       if (this._isUsableItem(id))
  5521.         this._appEnableItem(id);
  5522.     }
  5523.  
  5524.     items = ds.getBlocklistedItemList(null, null, Ci.nsIUpdateItem.TYPE_ANY,
  5525.                                       false);
  5526.     for (i = 0; i < items.length; ++i)
  5527.       this._appDisableItem(items[i].id);
  5528.  
  5529.     // show the blocklist notification window if there are new blocklist items.
  5530.     if (items.length > 0)
  5531.       showBlocklistMessage(items, false);
  5532.   },
  5533.  
  5534.   /**
  5535.    * @returns An enumeration of all registered Install Locations.
  5536.    */
  5537.   get installLocations () {
  5538.     return InstallLocations.enumeration;
  5539.   },
  5540.  
  5541.   /**
  5542.    * Gets the Install Location where a visible Item is stored.
  5543.    * @param   id
  5544.    *          The GUID of the item to locate an Install Location for.
  5545.    * @returns The Install Location object where the item is stored.
  5546.    */
  5547.   getInstallLocation: function(id) {
  5548.     var key = this.datasource.visibleItems[id];
  5549.     return key ? InstallLocations.get(this.datasource.visibleItems[id]) : null;
  5550.   },
  5551.  
  5552.   /**
  5553.    * Gets a nsIUpdateItem for the item with the specified id.
  5554.    * @param   id
  5555.    *          The GUID of the item to construct a nsIUpdateItem for.
  5556.    * @returns The nsIUpdateItem representing the item.
  5557.    */
  5558.   getItemForID: function(id) {
  5559.     return this.datasource.getItemForID(id);
  5560.   },
  5561.  
  5562.   /**
  5563.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  5564.    * on another item.
  5565.    * @param   id
  5566.    *          The ID of the item that other items depend on.
  5567.    * @param   includeDisabled
  5568.    *          Whether to include disabled items in the set returned.
  5569.    * @param   countRef
  5570.    *          The XPCJS reference to the number of items returned.
  5571.    * @returns An array of installed nsIUpdateItems that depend on the item
  5572.    *          specified by the id parameter.
  5573.    */
  5574.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  5575.     return this.datasource.getDependentItemListForID(id, includeDisabled, countRef);
  5576.   },
  5577.  
  5578.   /**
  5579.    * Retrieves a list of nsIUpdateItems of items matching the specified type.
  5580.    * @param   type
  5581.    *          The type of item to return.
  5582.    * @param   countRef
  5583.    *          The XPCJS reference to the number of items returned.
  5584.    * @returns An array of nsIUpdateItems matching the id/type filter.
  5585.    */
  5586.   getItemList: function(type, countRef) {
  5587.     return this.datasource.getItemList(type, countRef);
  5588.   },
  5589.  
  5590.   /* See nsIExtensionManager.idl */
  5591.   getIncompatibleItemList: function(id, appVersion, platformVersion, type, includeDisabled,
  5592.                                     countRef) {
  5593.     var items = this.datasource.getIncompatibleItemList(id, appVersion ? appVersion : undefined,
  5594.                                                         platformVersion ? platformVersion : undefined,
  5595.                                                         type, includeDisabled);
  5596.     countRef.value = items.length;
  5597.     return items;
  5598.   },
  5599.  
  5600.   /**
  5601.    * Move an Item to the index of another item in its container.
  5602.    * @param   movingID
  5603.    *          The ID of the item to be moved.
  5604.    * @param   destinationID
  5605.    *          The ID of an item to move another item to.
  5606.    */
  5607.   moveToIndexOf: function(movingID, destinationID) {
  5608.     this.datasource.moveToIndexOf(movingID, destinationID);
  5609.   },
  5610.  
  5611.   /**
  5612.    * Sorts addons of the specified type by the specified property starting from
  5613.    * the top of their container. If the addons are already sorted then no action
  5614.    * is performed.
  5615.    * @param   type
  5616.    *          The nsIUpdateItem type of the items to sort.
  5617.    * @param   propertyName
  5618.    *          The RDF property name used for sorting.
  5619.    * @param   isAscending
  5620.    *          true to sort ascending and false to sort descending
  5621.    */
  5622.   sortTypeByProperty: function(type, propertyName, isAscending) {
  5623.     this.datasource.sortTypeByProperty(type, propertyName, isAscending);
  5624.   },
  5625.  
  5626.   /////////////////////////////////////////////////////////////////////////////
  5627.   // Downloads
  5628.   _transactions: [],
  5629.   _downloadCount: 0,
  5630.   _compatibilityCheckCount: 0,
  5631.  
  5632.   /**
  5633.    * Ask the user if they really want to quit the application, since this will
  5634.    * cancel one or more Extension/Theme downloads.
  5635.    * @param   subject
  5636.    *          A nsISupportsPRBool which this function sets to false if the user
  5637.    *          wishes to cancel all active downloads and quit the application,
  5638.    *          false otherwise.
  5639.    */
  5640.   _confirmCancelDownloadsOnQuit: function(subject) {
  5641.     // If user has already dismissed quit request, then do nothing
  5642.     if ((subject instanceof Ci.nsISupportsPRBool) && subject.data)
  5643.       return;
  5644.  
  5645.     if (this._downloadCount > 0) {
  5646.       // The observers will be notified again after this so set the download
  5647.       // count to 0 to prevent this dialog from being displayed again.
  5648.       this._downloadCount = 0;
  5649.       var result;
  5650. //@line 5629 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  5651.       result = this._confirmCancelDownloads(this._downloadCount,
  5652.                                             "quitCancelDownloadsAlertTitle",
  5653.                                             "quitCancelDownloadsAlertMsgMultiple",
  5654.                                             "quitCancelDownloadsAlertMsg",
  5655.                                             "dontQuitButtonWin");
  5656. //@line 5641 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  5657.       if (subject instanceof Ci.nsISupportsPRBool)
  5658.         subject.data = result;
  5659.     }
  5660.   },
  5661.  
  5662.   /**
  5663.    * Ask the user if they really want to go offline, since this will cancel
  5664.    * one or more Extension/Theme downloads.
  5665.    * @param   subject
  5666.    *          A nsISupportsPRBool which this function sets to false if the user
  5667.    *          wishes to cancel all active downloads and go offline, false
  5668.    *          otherwise.
  5669.    */
  5670.   _confirmCancelDownloadsOnOffline: function(subject) {
  5671.     if (this._downloadCount > 0) {
  5672.       result = this._confirmCancelDownloads(this._downloadCount,
  5673.                                             "offlineCancelDownloadsAlertTitle",
  5674.                                             "offlineCancelDownloadsAlertMsgMultiple",
  5675.                                             "offlineCancelDownloadsAlertMsg",
  5676.                                             "dontGoOfflineButton");
  5677.       if (subject instanceof Ci.nsISupportsPRBool)
  5678.         subject.data = result;
  5679.     }
  5680.   },
  5681.  
  5682.   /**
  5683.    * Ask the user whether or not they wish to cancel the Extension/Theme
  5684.    * downloads which are currently under way.
  5685.    * @param   count
  5686.    *          The number of active downloads.
  5687.    * @param   title
  5688.    *          The key of the title for the message box to be displayed
  5689.    * @param   cancelMessageMultiple
  5690.    *          The key of the message to be displayed in the message box
  5691.    *          when there are > 1 active downloads.
  5692.    * @param   cancelMessageSingle
  5693.    *          The key of the message to be displayed in the message box
  5694.    *          when there is just one active download.
  5695.    * @param   dontCancelButton
  5696.    *          The key of the label to be displayed on the "Don't Cancel
  5697.    *          Downloads" button.
  5698.    */
  5699.   _confirmCancelDownloads: function(count, title, cancelMessageMultiple,
  5700.                                     cancelMessageSingle, dontCancelButton) {
  5701.     var bundle = BundleManager.getBundle(URI_DOWNLOADS_PROPERTIES);
  5702.     var title = bundle.GetStringFromName(title);
  5703.     var message, quitButton;
  5704.     if (count > 1) {
  5705.       message = bundle.formatStringFromName(cancelMessageMultiple, [count], 1);
  5706.       quitButton = bundle.formatStringFromName("cancelDownloadsOKTextMultiple", [count], 1);
  5707.     }
  5708.     else {
  5709.       message = bundle.GetStringFromName(cancelMessageSingle);
  5710.       quitButton = bundle.GetStringFromName("cancelDownloadsOKText");
  5711.     }
  5712.     var dontQuitButton = bundle.GetStringFromName(dontCancelButton);
  5713.  
  5714.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  5715.              getService(Ci.nsIWindowMediator);
  5716.     var win = wm.getMostRecentWindow("Extension:Manager");
  5717.     const nsIPromptService = Ci.nsIPromptService;
  5718.     var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  5719.              getService(nsIPromptService);
  5720.     var flags = (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_0) +
  5721.                 (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_1);
  5722.     var rv = ps.confirmEx(win, title, message, flags, quitButton, dontQuitButton, null, null, { });
  5723.     return rv == 1;
  5724.   },
  5725.  
  5726.   /* See nsIExtensionManager.idl */
  5727.   addDownloads: function(items, itemCount, manager) {
  5728.     if (itemCount == 0)
  5729.       throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5730.  
  5731.     for (i = 0; i < itemCount; ++i) {
  5732.       var currItem = items[i];
  5733.       if (!currItem)
  5734.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5735.     }
  5736.  
  5737.     var ds = this.datasource;
  5738.     // Add observers only if they aren't already added for an active download
  5739.     if (this._downloadCount == 0) {
  5740.       gOS.addObserver(this, "offline-requested", false);
  5741.       gOS.addObserver(this, "quit-application-requested", false);
  5742.     }
  5743.     this._downloadCount += itemCount;
  5744.  
  5745.     var urls = [];
  5746.     var hashes = [];
  5747.     var txnID = Math.round(Math.random() * 100);
  5748.     var txn = new ItemDownloadTransaction(this, txnID);
  5749.     for (var i = 0; i < itemCount; ++i) {
  5750.       var currItem = items[i];
  5751.  
  5752.       txn.addDownload(currItem);
  5753.       urls.push(currItem.xpiURL);
  5754.       hashes.push(currItem.xpiHash ? currItem.xpiHash : null);
  5755.       // if this is an update remove the update metadata to prevent it from
  5756.       // being updated during an install.
  5757.       if (!manager) {
  5758.         var id = currItem.id
  5759.         ds.setItemProperties(id, {
  5760.           availableUpdateURL: null,
  5761.           availableUpdateHash: null,
  5762.           availableUpdateVersion: null,
  5763.           availableUpdateInfo: null
  5764.         });
  5765.         ds.updateProperty(id, "availableUpdateURL");
  5766.         ds.updateProperty(id, "updateable");
  5767.       }
  5768.       var id = !manager ? PREFIX_ITEM_URI + currItem.id : currItem.xpiURL;
  5769.       ds.updateDownloadState(id, "waiting");
  5770.     }
  5771.     this._transactions.push(txn);
  5772.  
  5773.     if (manager) {
  5774.       // XPIManager initiated -- let it know we're ready
  5775.       manager.observe(txn, "xpinstall-progress", "open");
  5776.     }
  5777.     else {
  5778.       // Initiate an install from chrome
  5779.       var xpimgr = Cc["@mozilla.org/xpinstall/install-manager;1"].
  5780.                    createInstance(Ci.nsIXPInstallManager);
  5781.       xpimgr.initManagerWithHashes(urls, hashes, urls.length, txn);
  5782.     }
  5783.   },
  5784.  
  5785.   /**
  5786.    * Download Operation State has changed from one to another.
  5787.    *
  5788.    * The nsIXPIProgressDialog implementation in the download transaction object
  5789.    * forwards notifications through these methods which we then pass on to any
  5790.    * front end objects implementing nsIExtensionDownloadListener that
  5791.    * are listening. We maintain the master state of download operations HERE,
  5792.    * not in the front end, because if the user closes the extension or theme
  5793.    * managers during the downloads we need to maintain state and not terminate
  5794.    * the download/install process.
  5795.    *
  5796.    * @param   transaction
  5797.    *          The ItemDownloadTransaction object receiving the download
  5798.    *          notifications from XPInstall.
  5799.    * @param   addon
  5800.    *          An object representing nsIUpdateItem for the addon being updated
  5801.    * @param   state
  5802.    *          The state we are entering
  5803.    * @param   value
  5804.    *          ???
  5805.    */
  5806.   onStateChange: function(transaction, addon, state, value) {
  5807.     var ds = this.datasource;
  5808.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5809.     const nsIXPIProgressDialog = Ci.nsIXPIProgressDialog;
  5810.     switch (state) {
  5811.     case nsIXPIProgressDialog.DOWNLOAD_START:
  5812.       ds.updateDownloadState(id, "downloading");
  5813.       for (var i = 0; i < this._installListeners.length; ++i)
  5814.         this._installListeners[i].onDownloadStarted(addon);
  5815.       break;
  5816.     case nsIXPIProgressDialog.DOWNLOAD_DONE:
  5817.       for (var i = 0; i < this._installListeners.length; ++i)
  5818.         this._installListeners[i].onDownloadEnded(addon);
  5819.       break;
  5820.     case nsIXPIProgressDialog.INSTALL_START:
  5821.       ds.updateDownloadState(id, "finishing");
  5822.       ds.updateDownloadProgress(id, null);
  5823.       break;
  5824.     case nsIXPIProgressDialog.INSTALL_DONE:
  5825.       --this._downloadCount;
  5826.       // From nsInstall.h
  5827.       // SUCCESS        = 0
  5828.       // USER_CANCELLED = -210
  5829.       if (value != 0 && value != -210 && id != addon.xpiURL) {
  5830.         ds.updateDownloadState(id, "failure");
  5831.         ds.updateDownloadProgress(id, null);
  5832.       }
  5833.       transaction.removeDownload(addon.xpiURL);
  5834.       // A successful install will be passing notifications via installItemFromFile
  5835.       if (value != 0) {
  5836.         for (var i = 0; i < this._installListeners.length; ++i)
  5837.           this._installListeners[i].onInstallEnded(addon, value);
  5838.       }
  5839.       break;
  5840.     case nsIXPIProgressDialog.DIALOG_CLOSE:
  5841.       for (var i = 0; i < this._transactions.length; ++i) {
  5842.         if (this._transactions[i].id == transaction.id) {
  5843.           this._transactions.splice(i, 1);
  5844.           // Remove the observers when all transactions have completed.
  5845.           if (this._transactions.length == 0) {
  5846.             gOS.removeObserver(this, "offline-requested");
  5847.             gOS.removeObserver(this, "quit-application-requested");
  5848.  
  5849.             // If there are no compatibility checks running then the install
  5850.             // operations are complete.
  5851.             if (this._compatibilityCheckCount == 0) {
  5852.               for (var i = 0; i < this._installListeners.length; ++i)
  5853.                 this._installListeners[i].onInstallsCompleted();
  5854.             }
  5855.           }
  5856.           break;
  5857.         }
  5858.       }
  5859.       // Remove any remaining downloads from this transaction
  5860.       transaction.removeAllDownloads();
  5861.       break;
  5862.     }
  5863.   },
  5864.  
  5865.   onProgress: function(addon, value, maxValue) {
  5866.     for (var i = 0; i < this._installListeners.length; ++i)
  5867.       this._installListeners[i].onDownloadProgress(addon, value, maxValue);
  5868.  
  5869.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5870.     var progress = Math.round((value / maxValue) * 100);
  5871.     this.datasource.updateDownloadProgress(id, progress);
  5872.   },
  5873.  
  5874.   _installListeners: [],
  5875.   addInstallListener: function(listener) {
  5876.     for (var i = 0; i < this._installListeners.length; ++i) {
  5877.       if (this._installListeners[i] == listener)
  5878.         return i;
  5879.     }
  5880.     this._installListeners.push(listener);
  5881.     return this._installListeners.length - 1;
  5882.   },
  5883.  
  5884.   removeInstallListenerAt: function(index) {
  5885.     this._installListeners.splice(index, 1);
  5886.   },
  5887.  
  5888.   /**
  5889.    * The Extensions RDF Datasource
  5890.    */
  5891.   _ds: null,
  5892.   _ptr: null,
  5893.  
  5894.   /**
  5895.    * Loads the Extensions Datasource. This should not be called unless:
  5896.    * - a piece of Extensions UI is being shown, or
  5897.    * - on startup and there has been a change to an Install Location
  5898.    * ... it should NOT be called on every startup!
  5899.    */
  5900.   _ensureDS: function() {
  5901.     if (!this._ds) {
  5902.       this._ds = new ExtensionsDataSource(this);
  5903.       if (this._ds) {
  5904.         this._ds.loadExtensions();
  5905.         this._ptr = getContainer(this._ds, this._ds._itemRoot).DataSource;
  5906.         gRDF.RegisterDataSource(this._ptr, true);
  5907.       }
  5908.     }
  5909.   },
  5910.  
  5911.   /**
  5912.    * See nsIExtensionManager.idl
  5913.    */
  5914.   get datasource() {
  5915.     this._ensureDS();
  5916.     return this._ds.QueryInterface(Ci.nsIRDFDataSource);
  5917.   },
  5918.  
  5919.   // nsIClassInfo
  5920.   flags: Ci.nsIClassInfo.SINGLETON,
  5921.   implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
  5922.   getHelperForLanguage: function(language) null,
  5923.   getInterfaces: function(count) {
  5924.     var interfaces = [Ci.nsIExtensionManager, Ci.nsIObserver];
  5925.     count.value = interfaces.length;
  5926.     return interfaces;
  5927.   },
  5928.  
  5929.   classDescription: "Extension Manager",
  5930.   contractID: "@mozilla.org/extensions/manager;1",
  5931.   classID: Components.ID("{8A115FAA-7DCB-4e8f-979B-5F53472F51CF}"),
  5932.   _xpcom_categories: [{ category: "app-startup", service: true }],
  5933.   _xpcom_factory: EmFactory,
  5934.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIExtensionManager,
  5935.                                          Ci.nsITimerCallback,
  5936.                                          Ci.nsIObserver,
  5937.                                          Ci.nsIClassInfo])
  5938. };
  5939.  
  5940. /**
  5941.  * This object implements nsIXPIProgressDialog and represents a collection of
  5942.  * XPI/JAR download and install operations. There is one
  5943.  * ItemDownloadTransaction per back-end XPInstallManager object. We maintain
  5944.  * a collection of separate transaction objects because it's possible to have
  5945.  * multiple separate XPInstall download/install operations going on
  5946.  * simultaneously, each with its own XPInstallManager instance. For instance
  5947.  * you could start downloading two extensions and then download a theme. Each
  5948.  * of these operations would open the appropriate FE and have to be able to
  5949.  * track each operation independently.
  5950.  *
  5951.  * @constructor
  5952.  * @param   manager
  5953.  *          The extension manager creating this transaction
  5954.  * @param   id
  5955.  *          The integer identifier of this transaction
  5956.  */
  5957. function ItemDownloadTransaction(manager, id) {
  5958.   this._manager = manager;
  5959.   this._downloads = [];
  5960.   this.id = id;
  5961. }
  5962. ItemDownloadTransaction.prototype = {
  5963.   _manager    : null,
  5964.   _downloads  : [],
  5965.   id          : -1,
  5966.  
  5967.   /**
  5968.    * Add a download to this transaction
  5969.    * @param   addon
  5970.    *          An object implementing nsIUpdateItem for the item to be downloaded
  5971.    */
  5972.   addDownload: function(addon) {
  5973.     this._downloads.push({ addon: addon, waiting: true });
  5974.     this._manager.datasource.addDownload(addon);
  5975.   },
  5976.  
  5977.   /**
  5978.    * Removes a download from this transaction
  5979.    * @param   url
  5980.    *          The URL to remove
  5981.    */
  5982.   removeDownload: function(url) {
  5983.     this._manager.datasource.removeDownload(url);
  5984.   },
  5985.  
  5986.   /**
  5987.    * Remove all downloads from this transaction
  5988.    */
  5989.   removeAllDownloads: function() {
  5990.     for (var i = 0; i < this._downloads.length; ++i) {
  5991.       var addon = this._downloads[i].addon;
  5992.       this.removeDownload(addon.xpiURL);
  5993.     }
  5994.   },
  5995.  
  5996.   /**
  5997.    * Determine if this transaction is handling the download of a url.
  5998.    * @param   url
  5999.    *          The URL to look for
  6000.    * @returns true if this transaction is downloading the supplied url.
  6001.    */
  6002.   containsURL: function(url) {
  6003.     for (var i = 0; i < this._downloads.length; ++i) {
  6004.       if (this._downloads[i].addon.xpiURL == url)
  6005.         return true;
  6006.     }
  6007.     return false;
  6008.   },
  6009.  
  6010.   /**
  6011.    * See nsIXPIProgressDialog.idl
  6012.    */
  6013.   onStateChange: function(index, state, value) {
  6014.     this._manager.onStateChange(this, this._downloads[index].addon,
  6015.                                 state, value);
  6016.   },
  6017.  
  6018.   /**
  6019.    * See nsIXPIProgressDialog.idl
  6020.    */
  6021.   onProgress: function(index, value, maxValue) {
  6022.     this._manager.onProgress(this._downloads[index].addon, value, maxValue);
  6023.   },
  6024.  
  6025.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIXPIProgressDialog])
  6026. };
  6027.  
  6028. /**
  6029.  * A listener object that watches the background update check and notifies the
  6030.  * user of any updates found.
  6031.  */
  6032. function BackgroundUpdateCheckListener(datasource) {
  6033.   this._emDS = datasource;
  6034. }
  6035. BackgroundUpdateCheckListener.prototype = {
  6036.   _updateCount: 0,
  6037.   _emDS: null,
  6038.  
  6039.   // nsIObserver implementation
  6040.   observe: function(aSubject, aTopic, aData) {
  6041.     if (aTopic != "alertclickcallback")
  6042.       return;
  6043.  
  6044.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  6045.              getService(Ci.nsIWindowMediator);
  6046.     var win = wm.getMostRecentWindow("Extension:Manager");
  6047.     if (win) {
  6048.       win.focus();
  6049.       win.showView("updates");
  6050.       // Don't show the update notification on next startup
  6051.       gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  6052.     }
  6053.     else {
  6054.       const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  6055.       const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
  6056.  
  6057.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  6058.                getService(Ci.nsIWindowWatcher);
  6059.       var param = Cc["@mozilla.org/supports-array;1"].
  6060.                   createInstance(Ci.nsISupportsArray);
  6061.       var arg = Cc["@mozilla.org/supports-string;1"].
  6062.                 createInstance(Ci.nsISupportsString);
  6063.       arg.data = "updates";
  6064.       param.AppendElement(arg);
  6065.       ww.openWindow(null, EMURL, null, EMFEATURES, param);
  6066.     }
  6067.   },
  6068.   
  6069.   // nsIAddonUpdateCheckListener implementation
  6070.   onUpdateStarted: function() {
  6071.   },
  6072.  
  6073.   onUpdateEnded: function() {
  6074.     if (this._updateCount > 0 && Cc["@mozilla.org/alerts-service;1"]) {
  6075.       var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  6076.       var title = extensionStrings.GetStringFromName("updateNotificationTitle");
  6077.       var text;
  6078.       if (this._updateCount > 1)
  6079.         text = extensionStrings.formatStringFromName("multipleUpdateNotificationText",
  6080.                                                      [BundleManager.appName, this._updateCount], 2);
  6081.       else
  6082.         text = extensionStrings.formatStringFromName("updateNotificationText",
  6083.                                                      [BundleManager.appName], 1);
  6084.  
  6085.       try {
  6086.         var notifier = Cc["@mozilla.org/alerts-service;1"].
  6087.                        getService(Ci.nsIAlertsService);
  6088.         notifier.showAlertNotification(URI_GENERIC_ICON_XPINSTALL,
  6089.                                        title, text, true, "", this);
  6090.       }
  6091.       catch (e) {
  6092.         LOG("Failed to retrieve alerts service, probably an unsupported " +
  6093.             "platform - " + e);
  6094.       }
  6095.     }
  6096.   },
  6097.  
  6098.   onAddonUpdateStarted: function(item) {
  6099.   },
  6100.  
  6101.   onAddonUpdateEnded: function(item, status) {
  6102.     if (status == Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE) {
  6103.       var lastupdate = this._emDS.getItemProperty(item.id, "availableUpdateVersion");
  6104.       if (lastupdate != item.version) {
  6105.         gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, true);
  6106.         this._updateCount++;
  6107.       }
  6108.     }
  6109.   }
  6110. };
  6111.  
  6112.  
  6113. /**
  6114.  * A listener object to the update check process that routes notifications to
  6115.  * the right places and keeps the datasource up to date.
  6116.  */
  6117. function AddonUpdateCheckListener(listener, datasource) {
  6118.   this._listener = listener;
  6119.   this._ds = datasource;
  6120. }
  6121. AddonUpdateCheckListener.prototype = {
  6122.   _listener: null,
  6123.   _ds: null,
  6124.  
  6125.   onUpdateStarted: function() {
  6126.     if (this._listener)
  6127.       this._listener.onUpdateStarted();
  6128.     this._ds.onUpdateStarted();
  6129.   },
  6130.  
  6131.   onUpdateEnded: function() {
  6132.     if (this._listener)
  6133.       this._listener.onUpdateEnded();
  6134.     this._ds.onUpdateEnded();
  6135.   },
  6136.  
  6137.   onAddonUpdateStarted: function(addon) {
  6138.     if (this._listener)
  6139.       this._listener.onAddonUpdateStarted(addon);
  6140.     this._ds.onAddonUpdateStarted(addon);
  6141.   },
  6142.  
  6143.   onAddonUpdateEnded: function(addon, status) {
  6144.     if (this._listener)
  6145.       this._listener.onAddonUpdateEnded(addon, status);
  6146.     this._ds.onAddonUpdateEnded(addon, status);
  6147.   }
  6148. };
  6149.  
  6150. ///////////////////////////////////////////////////////////////////////////////
  6151. //
  6152. // ExtensionItemUpdater
  6153. //
  6154. function ExtensionItemUpdater(aEM)
  6155. {
  6156.   this._emDS = aEM._ds;
  6157.   this._em = aEM;
  6158.  
  6159.   getVersionChecker();
  6160. }
  6161.  
  6162. ExtensionItemUpdater.prototype = {
  6163.   _emDS               : null,
  6164.   _em                 : null,
  6165.   _updateCheckType    : 0,
  6166.   _items              : [],
  6167.   _listener           : null,
  6168.  
  6169.   /* ExtensionItemUpdater
  6170. //@line 6180 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  6171.   */
  6172.   checkForUpdates: function(aItems, aItemCount, aUpdateCheckType,
  6173.                             aListener) {
  6174.     this._listener = new AddonUpdateCheckListener(aListener, this._emDS);
  6175.     if (this._listener)
  6176.       this._listener.onUpdateStarted();
  6177.     this._updateCheckType = aUpdateCheckType;
  6178.     this._items = aItems;
  6179.     this._responseCount = aItemCount;
  6180.  
  6181.     // This is the number of extensions/themes/etc that we found updates for.
  6182.     this._updateCount = 0;
  6183.  
  6184.     for (var i = 0; i < aItemCount; ++i) {
  6185.       var e = this._items[i];
  6186.       if (this._listener)
  6187.         this._listener.onAddonUpdateStarted(e);
  6188.       (new RDFItemUpdater(this)).checkForUpdates(e, aUpdateCheckType);
  6189.     }
  6190.  
  6191.     if (this._listener && aItemCount == 0)
  6192.       this._listener.onUpdateEnded();
  6193.   },
  6194.  
  6195.   /////////////////////////////////////////////////////////////////////////////
  6196.   // ExtensionItemUpdater
  6197.   _applyVersionUpdates: function(aLocalItem, aRemoteItem) {
  6198.     var targetAppInfo = this._emDS.getTargetApplicationInfo(aLocalItem.id, this._emDS);
  6199.     // If targetAppInfo is null this is for a new install. If the local item's
  6200.     // maxVersion does not equal the targetAppInfo maxVersion then this is for
  6201.     // an upgrade. In both of these cases return true if the remotely specified
  6202.     // maxVersion is greater than the local item's maxVersion.
  6203.     if (!targetAppInfo ||
  6204.         gVersionChecker.compare(aLocalItem.maxAppVersion, targetAppInfo.maxVersion) != 0) {
  6205.       if (gVersionChecker.compare(aLocalItem.maxAppVersion, aRemoteItem.maxAppVersion) < 0)
  6206.         return true;
  6207.       else
  6208.         return false;
  6209.     }
  6210.  
  6211.     if (gVersionChecker.compare(targetAppInfo.maxVersion, aRemoteItem.maxAppVersion) < 0) {
  6212.       // Remotely specified maxVersion is newer than the maxVersion
  6213.       // for the installed Extension. Apply that change to the datasources.
  6214.       this._emDS.setTargetApplicationInfo(aLocalItem.id,
  6215.                                           aRemoteItem.targetAppID,
  6216.                                           aRemoteItem.minAppVersion,
  6217.                                           aRemoteItem.maxAppVersion,
  6218.                                           null);
  6219.  
  6220.       // If we got here through |checkForMismatches|, this extension has
  6221.       // already been disabled, re-enable it.
  6222.       var op = StartupCache.entries[aLocalItem.installLocationKey][aLocalItem.id].op;
  6223.       if (op == OP_NEEDS_DISABLE ||
  6224.           this._emDS.getItemProperty(aLocalItem.id, "appDisabled") == "true")
  6225.         this._em._appEnableItem(aLocalItem.id);
  6226.       return true;
  6227.     }
  6228.     else if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_SYNC_COMPATIBILITY)
  6229.       this._emDS.setTargetApplicationInfo(aLocalItem.id,
  6230.                                           aRemoteItem.targetAppID,
  6231.                                           aRemoteItem.minAppVersion,
  6232.                                           aRemoteItem.maxAppVersion,
  6233.                                           null);
  6234.     return false;
  6235.   },
  6236.  
  6237.   /**
  6238.    * Checks whether a discovered update is valid for install
  6239.    * @param   aLocalItem
  6240.    *          The already installed nsIUpdateItem that the update is for
  6241.    * @param   aRemoteItem
  6242.    *          The nsIUpdateItem we are trying to update to
  6243.    *
  6244.    * @returns true if the item is compatible and is not blocklisted.
  6245.    *          false if the item is not compatible or is blocklisted.
  6246.    */
  6247.   _isValidUpdate: function _isValidUpdate(aLocalItem, aRemoteItem) {
  6248.     var appExtensionsVersion = (aRemoteItem.targetAppID != TOOLKIT_ID) ?
  6249.                                gApp.version :
  6250.                                gApp.platformVersion;
  6251.  
  6252.     var min = aRemoteItem.minAppVersion;
  6253.     var max = aRemoteItem.maxAppVersion;
  6254.     // Check if the update will only run on a newer version of the application.
  6255.     if (!min || gVersionChecker.compare(appExtensionsVersion, min) < 0)
  6256.       return false;
  6257.  
  6258.     // Check if the update will only run on an older version of the application.
  6259.     if (!max || gVersionChecker.compare(appExtensionsVersion, max) > 0)
  6260.       return false;
  6261.  
  6262.     if (!gBlocklist)
  6263.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  6264.                    getService(Ci.nsIBlocklistService);
  6265.     if (gBlocklist.isAddonBlocklisted(aLocalItem.id, aRemoteItem.version,
  6266.                                       null, null))
  6267.       return false;
  6268.  
  6269.     return true;
  6270.   },
  6271.  
  6272.   checkForDone: function(item, status) {
  6273.     if (this._listener) {
  6274.       try {
  6275.         this._listener.onAddonUpdateEnded(item, status);
  6276.       }
  6277.       catch (e) {
  6278.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onAddonUpdateEnded: " + e);
  6279.       }
  6280.     }
  6281.     if (--this._responseCount == 0 && this._listener) {
  6282.       try {
  6283.         this._listener.onUpdateEnded();
  6284.       }
  6285.       catch (e) {
  6286.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onUpdateEnded: " + e);
  6287.       }
  6288.     }
  6289.   },
  6290. };
  6291.  
  6292. /**
  6293.  * Replaces %...% strings in an addon url (update and updateInfo) with
  6294.  * appropriate values.
  6295.  * @param   aItem
  6296.  *          The nsIUpdateItem representing the item
  6297.  * @param   aURI
  6298.  *          The uri to escape
  6299.  * @param   aDS
  6300.  *          The extensions datasource
  6301.  *
  6302.  * @returns the appropriately escaped uri.
  6303.  */
  6304. function escapeAddonURI(aItem, aURI, aDS)
  6305. {
  6306.   var itemStatus = "userEnabled";
  6307.   if (aDS.getItemProperty(aItem.id, "userDisabled") == "true" ||
  6308.       aDS.getItemProperty(aItem.id, "userDisabled") == OP_NEEDS_ENABLE)
  6309.     itemStatus = "userDisabled";
  6310.   else if (aDS.getItemProperty(aItem.id, "type") == Ci.nsIUpdateItem.TYPE_THEME) {
  6311.     var currentSkin = gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  6312.     if (aDS.getItemProperty(aItem.id, "internalName") != currentSkin)
  6313.       itemStatus = "userDisabled";
  6314.   }
  6315.  
  6316.   if (aDS.getItemProperty(aItem.id, "compatible") == "false")
  6317.     itemStatus += ",incompatible";
  6318.   if (aDS.getItemProperty(aItem.id, "blocklisted") == "true")
  6319.     itemStatus += ",blocklisted";
  6320.   if (aDS.getItemProperty(aItem.id, "satisfiesDependencies") == "false")
  6321.     itemStatus += ",needsDependencies";
  6322.  
  6323.   aURI = aURI.replace(/%ITEM_ID%/g, aItem.id);
  6324.   aURI = aURI.replace(/%ITEM_VERSION%/g, aItem.version);
  6325.   aURI = aURI.replace(/%ITEM_MAXAPPVERSION%/g, aItem.maxAppVersion);
  6326.   aURI = aURI.replace(/%ITEM_STATUS%/g, itemStatus);
  6327.   aURI = aURI.replace(/%APP_ID%/g, gApp.ID);
  6328.   aURI = aURI.replace(/%APP_VERSION%/g, gApp.version);
  6329.   aURI = aURI.replace(/%REQ_VERSION%/g, 1);
  6330.   aURI = aURI.replace(/%APP_OS%/g, gOSTarget);
  6331.   aURI = aURI.replace(/%APP_ABI%/g, gXPCOMABI);
  6332.   aURI = aURI.replace(/%APP_LOCALE%/g, gLocale);
  6333.  
  6334.   // Replace custom parameters (names of custom parameters must have at
  6335.   // least 3 characters to prevent lookups for something like %D0%C8)
  6336.   var catMan = null;
  6337.   aURI = aURI.replace(/%(\w{3,})%/g, function(match, param) {
  6338.     if (!catMan) {
  6339.       catMan = Cc["@mozilla.org/categorymanager;1"].
  6340.                getService(Ci.nsICategoryManager);
  6341.     }
  6342.  
  6343.     try {
  6344.       var contractID = catMan.getCategoryEntry(CATEGORY_UPDATE_PARAMS, param);
  6345.       var paramHandler = Cc[contractID].
  6346.                          getService(Ci.nsIPropertyBag2);
  6347.       return paramHandler.getPropertyAsAString(param);
  6348.     }
  6349.     catch(e) {
  6350.       return match;
  6351.     }
  6352.   });
  6353.  
  6354.   // escape() does not properly encode + symbols in any embedded FVF strings.
  6355.   return aURI.replace(/\+/g, "%2B");
  6356. }
  6357.  
  6358. function RDFItemUpdater(aUpdater) {
  6359.   this._updater = aUpdater;
  6360. }
  6361.  
  6362. RDFItemUpdater.prototype = {
  6363.   _updater            : null,
  6364.   _updateCheckType    : 0,
  6365.   _item               : null,
  6366.  
  6367.   checkForUpdates: function(aItem, aUpdateCheckType) {
  6368.     // A preference setting can disable updating for this item
  6369.     try {
  6370.       if (!gPref.getBoolPref(PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, aItem.id))) {
  6371.         var status = Ci.nsIAddonUpdateCheckListener.STATUS_DISABLED;
  6372.         this._updater.checkForDone(aItem, status);
  6373.         return;
  6374.       }
  6375.     }
  6376.     catch (e) { }
  6377.  
  6378.     // Items managed by the app are not checked for updates.
  6379.     var emDS = this._updater._emDS;
  6380.     if (emDS.getItemProperty(aItem.id, "appManaged") == "true") {
  6381.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_APP_MANAGED;
  6382.       this._updater.checkForDone(aItem, status);
  6383.       return;
  6384.     }
  6385.  
  6386.     // Items that have a pending install, uninstall, or upgrade are not checked
  6387.     // for updates.
  6388.     var opType = emDS.getItemProperty(aItem.id, "opType");
  6389.     if (opType) {
  6390.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_PENDING_OP;
  6391.       this._updater.checkForDone(aItem, status);
  6392.       return;
  6393.     }
  6394.  
  6395.     var installLocation = InstallLocations.get(emDS.getInstallLocationKey(aItem.id));
  6396.     // Don't check items for updates that are managed independently
  6397.     if (installLocation && installLocation.itemIsManagedIndependently(aItem.id)) {
  6398.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_NOT_MANAGED;
  6399.       this._updater.checkForDone(aItem, status);
  6400.       return;
  6401.     }
  6402.  
  6403.     // Don't check items for updates if the location can't be written to except
  6404.     // when performing a version only update.
  6405.     if ((aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) &&
  6406.         (!installLocation || !installLocation.canAccess)) {
  6407.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_READ_ONLY;
  6408.       this._updater.checkForDone(aItem, status);
  6409.       return;
  6410.     }
  6411.  
  6412.     this._updateCheckType = aUpdateCheckType;
  6413.     this._item = aItem;
  6414.  
  6415.     // Look for a custom update URI: 1) supplied by a pref, 2) supplied by the
  6416.     // install manifest, 3) the default configuration
  6417.     try {
  6418.       var dsURI = gPref.getComplexValue(PREF_EM_ITEM_UPDATE_URL.replace(/%UUID%/, aItem.id),
  6419.                                         Ci.nsIPrefLocalizedString).data;
  6420.     }
  6421.     catch (e) { }
  6422.     if (!dsURI)
  6423.       dsURI = aItem.updateRDF;
  6424.     if (!dsURI)
  6425.       dsURI = gPref.getCharPref(PREF_UPDATE_DEFAULT_URL);
  6426.  
  6427.     dsURI = escapeAddonURI(aItem, dsURI, emDS);
  6428.  
  6429.     // Verify that the URI provided is valid
  6430.     try {
  6431.       var uri = newURI(dsURI);
  6432.     }
  6433.     catch (e) {
  6434.       LOG("RDFItemUpdater:checkForUpdates: There was an error loading the \r\n" +
  6435.           " update datasource for: " + dsURI + ", item = " + aItem.id + ", error: " + e);
  6436.       this._updater.checkForDone(aItem,
  6437.                                  Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6438.       return;
  6439.     }
  6440.  
  6441.     LOG("RDFItemUpdater:checkForUpdates sending a request to server for: " +
  6442.         uri.spec + ", item = " + aItem.objectSource);
  6443.  
  6444.     var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
  6445.                   createInstance(Ci.nsIXMLHttpRequest);
  6446.     request.open("GET", uri.spec, true);
  6447.     request.channel.notificationCallbacks = new BadCertHandler();
  6448.     request.overrideMimeType("text/xml");
  6449.     request.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
  6450.  
  6451.     var self = this;
  6452.     request.onerror     = function(event) { self.onXMLError(event, aItem);    };
  6453.     request.onload      = function(event) { self.onXMLLoad(event, aItem);     };
  6454.     request.send(null);
  6455.   },
  6456.  
  6457.   onXMLLoad: function(aEvent, aItem) {
  6458.     var request = aEvent.target;
  6459.     try {
  6460.       checkCert(request.channel);
  6461.     }
  6462.     catch (e) {
  6463.       // This may be overly restrictive in two cases: corporate installations
  6464.       // with a corporate update server using an in-house CA cert (installed
  6465.       // but not "built-in") and lone developers hosting their updates on a
  6466.       // site with a self-signed cert (permanently accepted, otherwise the
  6467.       // BadCertHandler would prevent getting this far). Update checks will
  6468.       // fail in both these scenarios.
  6469.       // How else can we protect the vast majority of updates served from AMO
  6470.       // from the spoofing attack described in bug 340198 while allowing those
  6471.       // other cases? A "hackme" pref? Domain-control certs are cheap, getting
  6472.       // one should not be a barrier in either case.
  6473.       LOG("RDFItemUpdater::onXMLLoad: " + e);
  6474.       this._updater.checkForDone(aItem,
  6475.                                  Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6476.       return;
  6477.     }
  6478.     var responseXML = request.responseXML;
  6479.  
  6480.     // If the item does not have an update RDF and returns an error it is not
  6481.     // treated as a failure since all items without an updateURL are checked
  6482.     // for updates on AMO even if they are not hosted there.
  6483.     if (!responseXML || responseXML.documentElement.namespaceURI == XMLURI_PARSE_ERROR ||
  6484.         (request.status != 200 && request.status != 0)) {
  6485.       this._updater.checkForDone(aItem, (aItem.updateRDF ? Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE :
  6486.                                                            Ci.nsIAddonUpdateCheckListener.STATUS_NONE));
  6487.       return;
  6488.     }
  6489.  
  6490.     var rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
  6491.                     createInstance(Ci.nsIRDFXMLParser)
  6492.     var ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
  6493.              createInstance(Ci.nsIRDFDataSource);
  6494.     rdfParser.parseString(ds, request.channel.URI, request.responseText);
  6495.  
  6496.     this.onDatasourceLoaded(ds, aItem);
  6497.   },
  6498.  
  6499.   onXMLError: function(aEvent, aItem) {
  6500.     try {
  6501.       var request = aEvent.target;
  6502.       // the following may throw (e.g. a local file or timeout)
  6503.       var status = request.status;
  6504.     }
  6505.     catch (e) {
  6506.       request = aEvent.target.channel.QueryInterface(Ci.nsIRequest);
  6507.       status = request.status;
  6508.     }
  6509.     // this can fail when a network connection is not present.
  6510.     try {
  6511.       var statusText = request.statusText;
  6512.     }
  6513.     catch (e) {
  6514.       status = 0;
  6515.     }
  6516.     // When status is 0 we don't have a valid channel.
  6517.     if (status == 0)
  6518.       statusText = "nsIXMLHttpRequest channel unavailable";
  6519.  
  6520.     LOG("RDFItemUpdater:onError: There was an error loading the \r\n" +
  6521.         "the update datasource for item " + aItem.id + ", error: " + statusText);
  6522.     this._updater.checkForDone(aItem,
  6523.                                Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6524.   },
  6525.  
  6526.   onDatasourceLoaded: function(aDatasource, aLocalItem) {
  6527.     /*
  6528. //@line 6578 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  6529.     */
  6530.     if (!aDatasource.GetAllResources().hasMoreElements()) {
  6531.       LOG("RDFItemUpdater:onDatasourceLoaded: Datasource empty.\r\n" +
  6532.           "If you are an Extension developer and were expecting there to be\r\n" +
  6533.           "updates, this could mean any number of things, since the RDF system\r\n" +
  6534.           "doesn't give up much in the way of information when the load fails.\r\n" +
  6535.           "\r\nTry checking that: \r\n" +
  6536.           " 1. Your remote RDF file exists at the location.\r\n" +
  6537.           " 2. Your RDF file is valid XML (starts with <?xml version=\"1.0\"?>\r\n" +
  6538.           "    and loads in Firefox displaying pretty printed like other XML documents\r\n" +
  6539.           " 3. Your server is sending the data in the correct MIME\r\n" +
  6540.           "    type (text/xml)");
  6541.     }      
  6542.  
  6543.     // If we have an update key then the update manifest must be signed
  6544.     if (aLocalItem.updateKey) {
  6545.       var extensionRes = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6546.       LOG(extensionRes.Value);
  6547.       var signature = this._getPropertyFromResource(aDatasource, extensionRes, "signature", null);
  6548.       if (signature) {
  6549.         var serializer = new RDFSerializer();
  6550.         try {
  6551.           var updateString = serializer.serializeResource(aDatasource, extensionRes);
  6552.           var verifier = Cc["@mozilla.org/security/datasignatureverifier;1"].
  6553.                          getService(Ci.nsIDataSignatureVerifier);
  6554.           try {
  6555.             if (!verifier.verifyData(updateString, signature, aLocalItem.updateKey)) {
  6556.               LOG("RDFItemUpdater:onDatasourceLoaded: Update manifest for " +
  6557.                   aLocalItem.id + " failed signature check.");
  6558.               this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6559.               return;
  6560.             }
  6561.           }
  6562.           catch (e) {
  6563.             LOG("RDFItemUpdater:onDatasourceLoaded: Failed to verify signature for " +
  6564.                 aLocalItem.id + ". This indicates a malformed update key or signature.");
  6565.             this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6566.             return;
  6567.           }
  6568.         }
  6569.         catch (e) {
  6570.           LOG("RDFItemUpdater:onDatasourceLoaded: Failed to generate signature " +
  6571.               "string for " + aLocalItem.id + ". Serializer threw " + e);
  6572.           this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6573.           return;
  6574.         }
  6575.       }
  6576.       else {
  6577.         LOG("RDFItemUpdater:onDatasourceLoaded: Update manifest for " +
  6578.             aLocalItem.id + " did not contain a signature.");
  6579.         this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6580.         return;
  6581.       }
  6582.     }
  6583.     /* If there is no updateKey either the update was over SSL, or it is an old
  6584.      * addon that we are allowing a grace update. */
  6585.  
  6586.     // Parse the response RDF
  6587.     var newerItem, sameItem;
  6588.  
  6589.     // Firefox 1.0PR+ update.rdf format
  6590.     if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6591.       // Look for newer versions of this item, we only do this in "normal"
  6592.       // mode... see comment by ExtensionItemUpdater_checkForUpdates
  6593.       // about how we do this in all cases but Install Phone Home - which
  6594.       // only needs to do a version check.
  6595.       newerItem = this._parseV20UpdateInfo(aDatasource, aLocalItem,
  6596.                                            Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  6597.  
  6598.       if (newerItem) {
  6599.         ++this._updater._updateCount;
  6600.         LOG("RDFItemUpdater:onDatasourceLoaded: Found a newer version of this item:\r\n" +
  6601.             newerItem.objectSource);
  6602.       }
  6603.     }
  6604.  
  6605.     // Now look for updated version compatibility metadata for the currently
  6606.     // installed version...
  6607.     sameItem = this._parseV20UpdateInfo(aDatasource, aLocalItem,
  6608.                                         Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY);
  6609.  
  6610.     if (sameItem) {
  6611.       // Install-time updates are not written to the DS because there is no
  6612.       // entry yet, EM just uses the notifications to ascertain (by hand)
  6613.       // whether or not there is a remote maxVersion tweak that makes the
  6614.       // item being installed compatible.
  6615.       if (!this._updater._applyVersionUpdates(aLocalItem, sameItem))
  6616.         sameItem = null;
  6617.       else
  6618.         LOG("RDFItemUpdater:onDatasourceLoaded: Found info about the installed\r\n" +
  6619.             "version of this item: " + sameItem.objectSource);
  6620.     }
  6621.     var item = null, status = Ci.nsIAddonUpdateCheckListener.STATUS_NONE;
  6622.     if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION
  6623.         && newerItem) {
  6624.       item = newerItem;
  6625.       status = Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE;
  6626.     }
  6627.     else if (sameItem) {
  6628.       item = sameItem;
  6629.       status = Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO;
  6630.     }
  6631.     else {
  6632.       item = aLocalItem;
  6633.       status = Ci.nsIAddonUpdateCheckListener.STATUS_NO_UPDATE;
  6634.     }
  6635.     // Only one call of this._updater.checkForDone is needed for RDF
  6636.     // responses, since there is only one response per item.
  6637.     this._updater.checkForDone(item, status);
  6638.   },
  6639.  
  6640.   // Get a compulsory property from a resource. Reports an error if the
  6641.   // property was not present.
  6642.   _getPropertyFromResource: function(aDataSource, aSourceResource, aProperty, aLocalItem) {
  6643.     var rv;
  6644.     try {
  6645.       var property = gRDF.GetResource(EM_NS(aProperty));
  6646.       rv = stringData(aDataSource.GetTarget(aSourceResource, property, true));
  6647.       if (rv === undefined)
  6648.         throw Cr.NS_ERROR_FAILURE;
  6649.     }
  6650.     catch (e) {
  6651.       // XXXben show console message "aProperty" not found on aSourceResource.
  6652.       return null;
  6653.     }
  6654.     return rv;
  6655.   },
  6656.  
  6657.   /**
  6658.    * Parses the Firefox 1.0RC1+ update manifest format looking for new versions
  6659.    * of updated compatibility information about the given add-on.
  6660.    * @param   aDataSource
  6661.    *          The update manifest's datasource
  6662.    * @param   aLocalItem
  6663.    *          The nsIUpdateItem representing the add-on being checked for updates.
  6664.    * @param   aUpdateCheckType
  6665.    *          The type of update check being performed. See the constants in
  6666.    *          nsIExtensionManager
  6667.    * @returns An nsIUpdateItem holding the update's information if a valid
  6668.    *          update is found or null if not.
  6669.    */
  6670.   _parseV20UpdateInfo: function(aDataSource, aLocalItem, aUpdateCheckType) {
  6671.     var extensionRes  = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6672.  
  6673.     var updatesArc = gRDF.GetResource(EM_NS("updates"));
  6674.     var updates = aDataSource.GetTarget(extensionRes, updatesArc, true);
  6675.  
  6676.     try {
  6677.       updates = updates.QueryInterface(Ci.nsIRDFResource);
  6678.     }
  6679.     catch (e) {
  6680.       LOG("RDFItemUpdater:_parseV20UpdateInfo: No updates were found for:\r\n" +
  6681.           aLocalItem.id + "\r\n" +
  6682.           "If you are an Extension developer and were expecting there to be\r\n" +
  6683.           "updates, this could mean any number of things, since the RDF system\r\n" +
  6684.           "doesn't give up much in the way of information when the load fails.\r\n" +
  6685.           "\r\nTry checking that: \r\n" +
  6686.           " 1. Your RDF File is correct - e.g. check that there is a top level\r\n" +
  6687.           "    RDF Resource with a URI urn:mozilla:extension:{GUID}, and that\r\n" +
  6688.           "    the <em:updates> listed all have matching GUIDs.");
  6689.       return null;
  6690.     }
  6691.  
  6692.     // Track the newest update found
  6693.     var updatedItem = null;
  6694.  
  6695.     var cu = Cc["@mozilla.org/rdf/container-utils;1"].
  6696.              getService(Ci.nsIRDFContainerUtils);
  6697.     if (cu.IsContainer(aDataSource, updates)) {
  6698.       var ctr = getContainer(aDataSource, updates);
  6699.  
  6700.       var versions = ctr.GetElements();
  6701.       while (versions.hasMoreElements()) {
  6702.         // There are two different methodologies for collecting version
  6703.         // information depending on whether or not we've been invoked in
  6704.         // "version updates only" mode or "version+newest" mode.
  6705.         var version = versions.getNext().QueryInterface(Ci.nsIRDFResource);
  6706.         var foundItem = this._parseV20Update(aDataSource, version, aLocalItem,
  6707.                                              updatedItem ? updatedItem.version : aLocalItem.version,
  6708.                                              aUpdateCheckType);
  6709.         if (foundItem) {
  6710.           // When not checking for new versions we can bail out on the first
  6711.           // result.
  6712.           if (aUpdateCheckType)
  6713.             return foundItem;
  6714.           updatedItem = foundItem;
  6715.         }
  6716.       }
  6717.     }
  6718.     return updatedItem;
  6719.   },
  6720.  
  6721.   /**
  6722.    * Parses a single version's update entry looking for the best matching
  6723.    * targetApplication entry.
  6724.    * @param   aDataSource
  6725.    *          The update manifest's datasource
  6726.    * @param   aUpdateResource
  6727.    *          The nsIRDFResource of the update entry.
  6728.    * @param   aLocalItem
  6729.    *          The nsIUpdateItem representing the add-on being checked for updates.
  6730.    * @param   aNewestVersionFound
  6731.    *          When checking for new versions holds the newest version of this
  6732.    *          add-on that we know about. Otherwise holds the current version.
  6733.    * @param   aUpdateCheckType
  6734.    *          The type of update check being performed. See the constants in
  6735.    *          nsIExtensionManager
  6736.    * @returns An nsIUpdateItem holding the update's information if a valid
  6737.    *          update is found or null if not.
  6738.    */
  6739.   _parseV20Update: function(aDataSource, aUpdateResource, aLocalItem, aNewestVersionFound, aUpdateCheckType) {
  6740.     var version = this._getPropertyFromResource(aDataSource, aUpdateResource,
  6741.                                                 "version", aLocalItem);
  6742.     /* If we are looking for new versions then test whether this discovered
  6743.      * version is greater than any previously found update. Otherwise check
  6744.      * if this update is for the same version as we have installed. */
  6745.     var result = gVersionChecker.compare(version, aNewestVersionFound);
  6746.     if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION ? result <= 0 : result != 0)
  6747.       return null;
  6748.  
  6749.     var taArc = gRDF.GetResource(EM_NS("targetApplication"));
  6750.     var targetApps = aDataSource.GetTargets(aUpdateResource, taArc, true);
  6751.     
  6752.     // Track the best update we have found so far
  6753.     var newestUpdateItem = null;
  6754.     while (targetApps.hasMoreElements()) {
  6755.       var targetApp = targetApps.getNext().QueryInterface(Ci.nsIRDFResource);
  6756.       var appID = this._getPropertyFromResource(aDataSource, targetApp, "id", aLocalItem);
  6757.       if (appID != gApp.ID && appID != TOOLKIT_ID)
  6758.         continue;
  6759.  
  6760.       var updateLink = this._getPropertyFromResource(aDataSource, targetApp, "updateLink", aLocalItem);
  6761.       var updateHash = this._getPropertyFromResource(aDataSource, targetApp, "updateHash", aLocalItem);
  6762.       if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6763.         // New version information is useless without a link to get it from
  6764.         if (!updateLink)
  6765.           continue;
  6766.  
  6767.         /* If the update link is non-ssl and we do not have a hash or the hash
  6768.          * is of an insecure nature then we must ignore this update. Bypass
  6769.          * this if not checking update security. Currently we only consider
  6770.          * the sha hashing algorithms as secure. */
  6771.         if (gCheckUpdateSecurity && updateLink.substring(0, 6) != "https:" && 
  6772.             (!updateHash || updateHash.substring(0, 3) != "sha")) {
  6773.           LOG("RDFItemUpdater:_parseV20Update: Update for " + aLocalItem.id +
  6774.               " at " + updateLink + " ignored because it is insecure. updateLink " +
  6775.               " must be a https url or an updateHash must be specified.");
  6776.           continue;
  6777.         }
  6778.       }
  6779.  
  6780.       var updatedItem = makeItem(aLocalItem.id,
  6781.                                  version,
  6782.                                  aLocalItem.installLocationKey,
  6783.                                  this._getPropertyFromResource(aDataSource, targetApp, "minVersion", aLocalItem),
  6784.                                  this._getPropertyFromResource(aDataSource, targetApp, "maxVersion", aLocalItem),
  6785.                                  aLocalItem.name,
  6786.                                  updateLink,
  6787.                                  updateHash,
  6788.                                  "", /* Icon URL */
  6789.                                  "", /* RDF Update URL */
  6790.                                  "", /* Update Key */
  6791.                                  aLocalItem.type,
  6792.                                  appID);
  6793.  
  6794.       if (this._updater._isValidUpdate(aLocalItem, updatedItem)) {
  6795.         if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6796.           var infourl = this._getPropertyFromResource(aDataSource, targetApp,
  6797.                                                       "updateInfoURL");
  6798.           if (infourl)
  6799.             infourl = EM_L(infourl);
  6800.           this._updater._emDS.setItemProperty(aLocalItem.id,
  6801.                                               EM_R("availableUpdateInfo"),
  6802.                                               infourl);
  6803.         }
  6804.         if (appID == gApp.ID) {
  6805.           // App takes precedence over toolkit.  If we found the app, bail out.
  6806.           return updatedItem;
  6807.         }
  6808.         newestUpdateItem = updatedItem;
  6809.       }
  6810.     }
  6811.     return newestUpdateItem;
  6812.   }
  6813. };
  6814.  
  6815. /**
  6816.  * A serialisation method for RDF data that produces an identical string
  6817.  * provided that the RDF assertions match.
  6818.  * The serialisation is not complete, only assertions stemming from a given
  6819.  * resource are included, multiple references to the same resource are not
  6820.  * permitted, and the RDF prolog and epilog are not included.
  6821.  * RDF Blob and Date literals are not supported.
  6822.  */
  6823. function RDFSerializer()
  6824. {
  6825.   this.cUtils = Cc["@mozilla.org/rdf/container-utils;1"].
  6826.                 getService(Ci.nsIRDFContainerUtils);
  6827.   this.resources = [];
  6828. }
  6829.  
  6830. RDFSerializer.prototype = {
  6831.   INDENT: "  ",      // The indent used for pretty-printing
  6832.   resources: null,   // Array of the resources that have been found
  6833.   
  6834.   /**
  6835.    * Escapes characters from a string that should not appear in XML.
  6836.    * @param string     The string to be escaped
  6837.    * @returns a string with all characters invalid in XML character data
  6838.    *          converted to entity references.
  6839.    */
  6840.   escapeEntities: function(string)
  6841.   {
  6842.     string = string.replace(/&/g, "&");
  6843.     string = string.replace(/</g, "<");
  6844.     string = string.replace(/>/g, ">");
  6845.     string = string.replace(/"/g, """);
  6846.     return string;
  6847.   },
  6848.   
  6849.   /**
  6850.    * Serializes all the elements of an RDF container.
  6851.    * @param ds         The datasource holding the data
  6852.    * @param container  The RDF container to output the child elements of
  6853.    * @param indent     The current level of indent for pretty-printing
  6854.    * @returns a string containing the serialized elements.
  6855.    */
  6856.   serializeContainerItems: function(ds, container, indent)
  6857.   {
  6858.     var result = "";
  6859.     var items = container.GetElements();
  6860.     while (items.hasMoreElements()) {
  6861.       var item = items.getNext().QueryInterface(Ci.nsIRDFResource);
  6862.       result += indent + "<RDF:li>\n"
  6863.       result += this.serializeResource(ds, item, indent + this.INDENT);
  6864.       result += indent + "</RDF:li>\n"
  6865.     }
  6866.     return result;
  6867.   },
  6868.   
  6869.   /**
  6870.    * Serializes all em:* (see EM_NS) properties of an RDF resource except for
  6871.    * the em:signature property. As this serialization is to be compared against
  6872.    * the manifest signature it cannot contain the em:signature property itself.
  6873.    * @param ds         The datasource holding the data
  6874.    * @param resource   The RDF resource to output the properties of
  6875.    * @param indent     The current level of indent for pretty-printing
  6876.    * @returns a string containing the serialized properties.
  6877.    */
  6878.   serializeResourceProperties: function(ds, resource, indent)
  6879.   {
  6880.     var result = "";
  6881.     var items = [];
  6882.     var arcs = ds.ArcLabelsOut(resource);
  6883.     while (arcs.hasMoreElements()) {
  6884.       var arc = arcs.getNext().QueryInterface(Ci.nsIRDFResource);
  6885.       if (arc.ValueUTF8.substring(0, PREFIX_NS_EM.length) != PREFIX_NS_EM)
  6886.         continue;
  6887.       var prop = arc.ValueUTF8.substring(PREFIX_NS_EM.length);
  6888.       if (prop == "signature")
  6889.         continue;
  6890.   
  6891.       var targets = ds.GetTargets(resource, arc, true);
  6892.       while (targets.hasMoreElements()) {
  6893.         var target = targets.getNext();
  6894.         if (target instanceof Ci.nsIRDFResource) {
  6895.           var item = indent + "<em:" + prop + ">\n";
  6896.           item += this.serializeResource(ds, target, indent + this.INDENT);
  6897.           item += indent + "</em:" + prop + ">\n";
  6898.           items.push(item);
  6899.         }
  6900.         else if (target instanceof Ci.nsIRDFLiteral) {
  6901.           items.push(indent + "<em:" + prop + ">" + this.escapeEntities(target.Value) + "</em:" + prop + ">\n");
  6902.         }
  6903.         else if (target instanceof Ci.nsIRDFInt) {
  6904.           items.push(indent + "<em:" + prop + " NC:parseType=\"Integer\">" + target.Value + "</em:" + prop + ">\n");
  6905.         }
  6906.         else {
  6907.           throw new Error("Cannot serialize unknown literal type");
  6908.         }
  6909.       }
  6910.     }
  6911.     items.sort();
  6912.     result += items.join("");
  6913.     return result;
  6914.   },
  6915.   
  6916.   /**
  6917.    * Recursively serializes an RDF resource and all resources it links to.
  6918.    * This will only output EM_NS properties and will ignore any em:signature
  6919.    * property.
  6920.    * @param ds         The datasource holding the data
  6921.    * @param resource   The RDF resource to serialize
  6922.    * @param indent     The current level of indent for pretty-printing.
  6923.    *                   Leave undefined for no indent
  6924.    * @returns a string containing the serialized resource.
  6925.    * @throws if the RDF data contains multiple references to the same resource.
  6926.    */
  6927.   serializeResource: function(ds, resource, indent)
  6928.   {
  6929.     if (this.resources.indexOf(resource) != -1 ) {
  6930.       // We cannot output multiple references to the same resource.
  6931.       throw new Error("Cannot serialize multiple references to "+resource.Value);
  6932.     }
  6933.     if (indent === undefined)
  6934.       indent = "";
  6935.     
  6936.     this.resources.push(resource);
  6937.     var container = null;
  6938.     var type = "Description";
  6939.     if (this.cUtils.IsSeq(ds, resource)) {
  6940.       type = "Seq";
  6941.       container = this.cUtils.MakeSeq(ds, resource);
  6942.     }
  6943.     else if (this.cUtils.IsAlt(ds, resource)) {
  6944.       type = "Alt";
  6945.       container = this.cUtils.MakeAlt(ds, resource);
  6946.     }
  6947.     else if (this.cUtils.IsBag(ds, resource)) {
  6948.       type = "Bag";
  6949.       container = this.cUtils.MakeBag(ds, resource);
  6950.     }
  6951.   
  6952.     var result = indent + "<RDF:" + type;
  6953.     if (!gRDF.IsAnonymousResource(resource))
  6954.       result += " about=\"" + this.escapeEntities(resource.ValueUTF8) + "\"";
  6955.     result += ">\n";
  6956.   
  6957.     if (container)
  6958.       result += this.serializeContainerItems(ds, container, indent + this.INDENT);
  6959.       
  6960.     result += this.serializeResourceProperties(ds, resource, indent + this.INDENT);
  6961.   
  6962.     result += indent + "</RDF:" + type + ">\n";
  6963.     return result;
  6964.   }
  6965. }
  6966.  
  6967. /**
  6968.  * A Datasource that holds Extensions.
  6969.  * - Implements nsIRDFDataSource to drive UI
  6970.  * - Uses a RDF/XML datasource for storage (this is undesirable)
  6971.  *
  6972.  * @constructor
  6973.  */
  6974. function ExtensionsDataSource(em) {
  6975.   this._em = em;
  6976.  
  6977.   this._itemRoot = gRDF.GetResource(RDFURI_ITEM_ROOT);
  6978.   this._defaultTheme = gRDF.GetResource(RDFURI_DEFAULT_THEME);
  6979. }
  6980. ExtensionsDataSource.prototype = {
  6981.   _inner    : null,
  6982.   _em       : null,
  6983.   _itemRoot     : null,
  6984.   _defaultTheme : null,
  6985.  
  6986.   /**
  6987.    * Determines if an item's dependencies are satisfied. An item's dependencies
  6988.    * are satisifed when all items specified in the item's em:requires arc are
  6989.    * installed, enabled, and the version is compatible based on the em:requires
  6990.    * minVersion and maxVersion.
  6991.    * @param   id
  6992.    *          The ID of the item
  6993.    * @returns true if the item's dependencies are satisfied.
  6994.    *          false if the item's dependencies are not satisfied.
  6995.    */
  6996.   satisfiesDependencies: function(id) {
  6997.     var ds = this._inner;
  6998.     var itemResource = getResourceForID(id);
  6999.     var targets = ds.GetTargets(itemResource, EM_R("requires"), true);
  7000.     if (!targets.hasMoreElements())
  7001.       return true;
  7002.  
  7003.     getVersionChecker();
  7004.     var idRes = EM_R("id");
  7005.     var minVersionRes = EM_R("minVersion");
  7006.     var maxVersionRes = EM_R("maxVersion");
  7007.     while (targets.hasMoreElements()) {
  7008.       var target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  7009.       var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  7010.       var version = null;
  7011.       version = this.getItemProperty(dependencyID, "version");
  7012.       if (version) {
  7013.         var opType = this.getItemProperty(dependencyID, "opType");
  7014.         if (opType ==  OP_NEEDS_DISABLE || opType == OP_NEEDS_UNINSTALL)
  7015.           return false;
  7016.  
  7017.         if (this.getItemProperty(dependencyID, "userDisabled") == "true" ||
  7018.             this.getItemProperty(dependencyID, "appDisabled") == "true" ||
  7019.             this.getItemProperty(dependencyID, "userDisabled") == OP_NEEDS_DISABLE ||
  7020.             this.getItemProperty(dependencyID, "appDisabled") == OP_NEEDS_DISABLE)
  7021.           return false;
  7022.  
  7023.         var minVersion = stringData(ds.GetTarget(target, minVersionRes, true));
  7024.         var maxVersion = stringData(ds.GetTarget(target, maxVersionRes, true));
  7025.         var compatible = (gVersionChecker.compare(version, minVersion) >= 0 &&
  7026.                           gVersionChecker.compare(version, maxVersion) <= 0);
  7027.         if (!compatible)
  7028.           return false;
  7029.       }
  7030.       else {
  7031.         return false;
  7032.       }
  7033.     }
  7034.  
  7035.     return true;
  7036.   },
  7037.  
  7038.   /**
  7039.    * Determine if an item is compatible
  7040.    * @param   datasource
  7041.    *          The datasource to inspect for compatibility - can be the main
  7042.    *          datasource or an Install Manifest.
  7043.    * @param   source
  7044.    *          The RDF Resource of the item to inspect for compatibility.
  7045.    * @param   appVersion
  7046.    *          The version of the application we are checking for compatibility
  7047.    *          against. If this parameter is undefined, the version of the running
  7048.    *          application is used.
  7049.    * @param   platformVersion
  7050.    *          The version of the toolkit to check compatibility against
  7051.    * @returns true if the item is compatible with this version of the
  7052.    *          application, false, otherwise.
  7053.    */
  7054.   isCompatible: function (datasource, source, appVersion, platformVersion) {
  7055.     // The Default Theme is always compatible.
  7056.     if (source.EqualsNode(this._defaultTheme))
  7057.       return true;
  7058.  
  7059.     var appID = gApp.ID;
  7060.     if (appVersion === undefined)
  7061.       appVersion = gApp.version;
  7062.     if (platformVersion === undefined)
  7063.       var platformVersion = gApp.platformVersion;
  7064.  
  7065.     var targets = datasource.GetTargets(source, EM_R("targetApplication"), true);
  7066.     var idRes = EM_R("id");
  7067.     var minVersionRes = EM_R("minVersion");
  7068.     var maxVersionRes = EM_R("maxVersion");
  7069.     var versionChecker = getVersionChecker();
  7070.     var rv = false;
  7071.     while (targets.hasMoreElements()) {
  7072.       var targetApp = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  7073.       var id          = stringData(datasource.GetTarget(targetApp, idRes, true));
  7074.       var minVersion  = stringData(datasource.GetTarget(targetApp, minVersionRes, true));
  7075.       var maxVersion  = stringData(datasource.GetTarget(targetApp, maxVersionRes, true));
  7076.       if (id == appID) {
  7077.         rv = (versionChecker.compare(appVersion, minVersion) >= 0) &&
  7078.              (versionChecker.compare(appVersion, maxVersion) <= 0);
  7079.         return rv; // App takes precedence over toolkit.
  7080.       }
  7081.  
  7082.       if (id == TOOLKIT_ID) {
  7083.         rv =  (versionChecker.compare(platformVersion, minVersion) >= 0) &&
  7084.               (versionChecker.compare(platformVersion, maxVersion) <= 0);
  7085.         // Keep looping, in case the app id is later.
  7086.       }
  7087.     }
  7088.     return rv;
  7089.   },
  7090.  
  7091.   /**
  7092.    * Gets a list of items that are incompatible with a specific application version.
  7093.    * @param   appID
  7094.    *          The ID of the application - XXXben unused?
  7095.    * @param   appVersion
  7096.    *          The Version of the application to check for incompatibility against.
  7097.    * @param   platformVersion
  7098.    *          The version of the toolkit to check compatibility against
  7099.    * @param   desiredType
  7100.    *          The nsIUpdateItem type of items to look for
  7101.    * @param   includeDisabled
  7102.    *          Whether or not disabled items should be included in the set returned
  7103.    * @returns An array of nsIUpdateItems that are incompatible with the application
  7104.    *          ID/Version supplied.
  7105.    */
  7106.   getIncompatibleItemList: function(appID, appVersion, platformVersion,
  7107.                                     desiredType, includeDisabled) {
  7108.     var items = [];
  7109.     var ctr = getContainer(this._inner, this._itemRoot);
  7110.     var elements = ctr.GetElements();
  7111.     while (elements.hasMoreElements()) {
  7112.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7113.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7114.       var type = this.getItemProperty(id, "type");
  7115.       // Skip this item if we're not seeking disabled items
  7116.       if (!includeDisabled && this.getItemProperty(id, "isDisabled") == "true")
  7117.         continue;
  7118.  
  7119.       // If the id of this item matches one of the items potentially installed
  7120.       // with and maintained by this application AND it is installed in the
  7121.       // global install location (i.e. the place installed by the app installer)
  7122.       // it is and can be managed by the update file - it's not an item that has
  7123.       // been manually installed by the user into their profile dir, and as such
  7124.       // it is always compatible with the next release of the application since
  7125.       // we will continue to support it.
  7126.       var locationKey = this.getItemProperty(id, "installLocation");
  7127.       var appManaged = this.getItemProperty(id, "appManaged") == "true";
  7128.       if (appManaged && locationKey == KEY_APP_GLOBAL)
  7129.         continue;
  7130.  
  7131.       if (type != -1 && (type & desiredType) &&
  7132.           !this.isCompatible(this, item, appVersion, platformVersion))
  7133.         items.push(this.getItemForID(id));
  7134.     }
  7135.     return items;
  7136.   },
  7137.  
  7138.   /**
  7139.    * Retrieves a list of items that will be blocklisted by the application for
  7140.    * a specific application or toolkit version.
  7141.    * @param   appVersion
  7142.    *          The Version of the application to check the blocklist against.
  7143.    * @param   platformVersion
  7144.    *          The Version of the toolkit to check the blocklist against.
  7145.    * @param   desiredType
  7146.    *          The nsIUpdateItem type of items to look for
  7147.    * @param   includeAppDisabled
  7148.    *          Whether or not items that are or are already set to be disabled
  7149.    *          by the app on next restart should be included in the set returned
  7150.    * @returns An array of nsIUpdateItems that are blocklisted with the application
  7151.    *          or toolkit version supplied.
  7152.    */
  7153.   getBlocklistedItemList: function(appVersion, platformVersion, desiredType,
  7154.                                    includeAppDisabled) {
  7155.     if (!gBlocklist)
  7156.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  7157.                    getService(Ci.nsIBlocklistService);
  7158.     var items = [];
  7159.     var ctr = getContainer(this._inner, this._itemRoot);
  7160.     var elements = ctr.GetElements();
  7161.     while (elements.hasMoreElements()) {
  7162.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7163.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7164.       var type = this.getItemProperty(id, "type");
  7165.  
  7166.       if (!includeAppDisabled &&
  7167.           (this.getItemProperty(id, "appDisabled") == "true" ||
  7168.           this.getItemProperty(id, "appDisabled") == OP_NEEDS_DISABLE))
  7169.         continue;
  7170.  
  7171.       var version = this.getItemProperty(id, "version");
  7172.       if (type != -1 && (type & desiredType) &&
  7173.           gBlocklist.isAddonBlocklisted(id, version, appVersion, platformVersion))
  7174.         items.push(this.getItemForID(id));
  7175.     }
  7176.     return items;
  7177.   },
  7178.  
  7179.   /**
  7180.    * Gets a list of items of a specific type
  7181.    * @param   desiredType
  7182.    *          The nsIUpdateItem type of items to return
  7183.    * @param   countRef
  7184.    *          The XPCJS reference to the size of the returned array
  7185.    * @returns An array of nsIUpdateItems, populated only with an item for |id|
  7186.    *          if |id| is non-null, otherwise all items matching the specified
  7187.    *          type.
  7188.    */
  7189.   getItemList: function(desiredType, countRef) {
  7190.     var items = [];
  7191.     var ctr = getContainer(this, this._itemRoot);
  7192.     var elements = ctr.GetElements();
  7193.     while (elements.hasMoreElements()) {
  7194.       var e = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7195.       var eID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  7196.       var type = this.getItemProperty(eID, "type");
  7197.       if (type != -1 && type & desiredType)
  7198.         items.push(this.getItemForID(eID));
  7199.     }
  7200.     countRef.value = items.length;
  7201.     return items;
  7202.   },
  7203.  
  7204.   /**
  7205.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  7206.    * on another item.
  7207.    * @param   id
  7208.    *          The ID of the item that other items depend on.
  7209.    * @param   includeDisabled
  7210.    *          Whether to include disabled items in the set returned.
  7211.    * @param   countRef
  7212.    *          The XPCJS reference to the number of items returned.
  7213.    * @returns An array of installed nsIUpdateItems that depend on the item
  7214.    *          specified by the id parameter.
  7215.    */
  7216.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  7217.     var items = [];
  7218.     var ds = this._inner;
  7219.     var ctr = getContainer(this, this._itemRoot);
  7220.     var elements = ctr.GetElements();
  7221.     while (elements.hasMoreElements()) {
  7222.       var e = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7223.       var dependentID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  7224.       var targets = ds.GetTargets(e, EM_R("requires"), true);
  7225.       var idRes = EM_R("id");
  7226.       while (targets.hasMoreElements()) {
  7227.         var target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  7228.         var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  7229.         if (dependencyID == id) {
  7230.           if (!includeDisabled && this.getItemProperty(dependentID, "isDisabled") == "true")
  7231.             continue;
  7232.           items.push(this.getItemForID(dependentID));
  7233.           break;
  7234.         }
  7235.       }
  7236.     }
  7237.     countRef.value = items.length;
  7238.     return items;
  7239.   },
  7240.  
  7241.   /**
  7242.    * Constructs an nsIUpdateItem for the given item ID
  7243.    * @param   id
  7244.    *          The GUID of the item to construct a nsIUpdateItem for
  7245.    * @returns The nsIUpdateItem for the id.
  7246.    */
  7247.   getItemForID: function(id) {
  7248.     if (!this.visibleItems[id])
  7249.       return null;
  7250.  
  7251.     var r = getResourceForID(id);
  7252.     if (!r)
  7253.       return null;
  7254.  
  7255.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  7256.     var updateHash = this.getItemProperty(id, "availableUpdateHash");
  7257.     return makeItem(id,
  7258.                     this.getItemProperty(id, "version"),
  7259.                     this.getItemProperty(id, "installLocation"),
  7260.                     targetAppInfo ? targetAppInfo.minVersion : "",
  7261.                     targetAppInfo ? targetAppInfo.maxVersion : "",
  7262.                     this.getItemProperty(id, "name"),
  7263.                     this.getItemProperty(id, "availableUpdateURL"),
  7264.                     updateHash ? updateHash : "",
  7265.                     this.getItemProperty(id, "iconURL"),
  7266.                     this.getItemProperty(id, "updateURL"),
  7267.                     this.getItemProperty(id, "updateKey"),
  7268.                     this.getItemProperty(id, "type"),
  7269.                     targetAppInfo ? targetAppInfo.appID : gApp.ID);
  7270.   },
  7271.  
  7272.   /**
  7273.    * Gets the name of the Install Location where an item is installed.
  7274.    * @param   id
  7275.    *          The GUID of the item to locate an Install Location for
  7276.    * @returns The string name of the Install Location where the item is
  7277.    *          installed.
  7278.    */
  7279.   getInstallLocationKey: function(id) {
  7280.     return this.getItemProperty(id, "installLocation");
  7281.   },
  7282.  
  7283.   /**
  7284.    * Sets an RDF property on an item in a datasource. Does not create
  7285.    * multiple assertions
  7286.    * @param   datasource
  7287.    *          The target datasource where the property should be set
  7288.    * @param   source
  7289.    *          The RDF Resource to set the property on
  7290.    * @param   property
  7291.    *          The RDF Resource of the property to set
  7292.    * @param   newValue
  7293.    *          The RDF Node containing the new property value
  7294.    */
  7295.   _setProperty: function(datasource, source, property, newValue) {
  7296.     var oldValue = datasource.GetTarget(source, property, true);
  7297.     if (oldValue) {
  7298.       if (newValue)
  7299.         datasource.Change(source, property, oldValue, newValue);
  7300.       else
  7301.         datasource.Unassert(source, property, oldValue);
  7302.     }
  7303.     else if (newValue)
  7304.       datasource.Assert(source, property, newValue, true);
  7305.   },
  7306.  
  7307.   /**
  7308.    * Gets the updated target application info if it exists for an item from
  7309.    * the Extensions datasource during an installation or upgrade.
  7310.    * @param   id
  7311.    *          The ID of the item to discover updated target application info for
  7312.    * @returns A JS Object with the following properties:
  7313.    *          "id"            The id of the item
  7314.    *          "minVersion"    The updated minimum version of the target
  7315.    *                          application that this item can run in
  7316.    *          "maxVersion"    The updated maximum version of the target
  7317.    *                          application that this item can run in
  7318.    */
  7319.   getUpdatedTargetAppInfo: function(id) {
  7320.     // The default theme is always compatible so there is never update info.
  7321.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  7322.       return null;
  7323.  
  7324.     var appID = gApp.ID;
  7325.     var r = getResourceForID(id);
  7326.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  7327.     if (!targetApps.hasMoreElements())
  7328.       targetApps = this._inner.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7329.     var outData = null;
  7330.     while (targetApps.hasMoreElements()) {
  7331.       var targetApp = targetApps.getNext();
  7332.       if (targetApp instanceof Ci.nsIRDFResource) {
  7333.         try {
  7334.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  7335.           // Different target application?
  7336.           if (foundAppID != appID && foundAppID != TOOLKIT_ID)
  7337.             continue;
  7338.           var updatedMinVersion = this._inner.GetTarget(targetApp, EM_R("updatedMinVersion"), true);
  7339.           var updatedMaxVersion = this._inner.GetTarget(targetApp, EM_R("updatedMaxVersion"), true);
  7340.           if (updatedMinVersion && updatedMaxVersion)
  7341.             outData = { id          : id,
  7342.                         targetAppID : foundAppID,
  7343.                         minVersion  : stringData(updatedMinVersion),
  7344.                         maxVersion  : stringData(updatedMaxVersion) };
  7345.           if (foundAppID == appID)
  7346.             return outData;
  7347.         }
  7348.         catch (e) {
  7349.           continue;
  7350.         }
  7351.       }
  7352.     }
  7353.     return outData;
  7354.   },
  7355.  
  7356.   /**
  7357.    * Sets the updated target application info for an item in the Extensions
  7358.    * datasource during an installation or upgrade.
  7359.    * @param   id
  7360.    *          The ID of the item to set updated target application info for
  7361.    * @param   targetAppID
  7362.    *          The target application ID used for checking compatibility for this item.
  7363.    * @param   updatedMinVersion
  7364.    *          The updated minimum version of the target application that this
  7365.    *          item can run in
  7366.    * @param   updatedMaxVersion
  7367.    *          The updated maximum version of the target application that this
  7368.    *          item can run in
  7369.    *
  7370.    * @note Add-ons can specify a targetApplication id of toolkit@mozilla.org in
  7371.    *       their install manifest for compatibility with all apps using a
  7372.    *       specific release of the toolkit.
  7373.    */
  7374.   setUpdatedTargetAppInfo: function(id, targetAppID, updatedMinVersion, updatedMaxVersion) {
  7375.     // The default theme is always compatible so it is never updated.
  7376.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  7377.       return;
  7378.  
  7379.     // Version/Dependency Info
  7380.     var updatedMinVersionRes = EM_R("updatedMinVersion");
  7381.     var updatedMaxVersionRes = EM_R("updatedMaxVersion");
  7382.  
  7383.     var appID = gApp.ID;
  7384.     var r = getResourceForID(id);
  7385.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  7386.     // add updatedMinVersion and updatedMaxVersion for an install else an upgrade
  7387.     if (!targetApps.hasMoreElements()) {
  7388.       var idRes = EM_R("id");
  7389.       var targetRes = getResourceForID(id);
  7390.       var property = EM_R("targetApplication");
  7391.       var anon = gRDF.GetAnonymousResource();
  7392.       this._inner.Assert(anon, idRes, EM_L(appID), true);
  7393.       this._inner.Assert(anon, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  7394.       this._inner.Assert(anon, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  7395.       this._inner.Assert(targetRes, property, anon, true);
  7396.     }
  7397.     else {
  7398.       while (targetApps.hasMoreElements()) {
  7399.         var targetApp = targetApps.getNext();
  7400.         if (targetApp instanceof Ci.nsIRDFResource) {
  7401.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  7402.           // Different target application?
  7403.           if (foundAppID != targetAppID)
  7404.             continue;
  7405.           this._inner.Assert(targetApp, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  7406.           this._inner.Assert(targetApp, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  7407.           break;
  7408.         }
  7409.       }
  7410.     }
  7411.     this.Flush();
  7412.   },
  7413.  
  7414.   /**
  7415.    * Gets the target application info for an item from a datasource.
  7416.    * @param   id
  7417.    *          The GUID of the item to discover target application info for
  7418.    * @param   datasource
  7419.    *          The datasource to look up target application info in
  7420.    * @returns A JS Object with the following properties:
  7421.    *          "appID"         The target application ID used for checking
  7422.    *                          compatibility for this item.
  7423.    *          "minVersion"    The minimum version of the target application
  7424.    *                          that this item can run in
  7425.    *          "maxVersion"    The maximum version of the target application
  7426.    *                          that this item can run in
  7427.    *          or null, if no target application data exists for the specified
  7428.    *          id in the supplied datasource.
  7429.    */
  7430.   getTargetApplicationInfo: function(id, datasource) {
  7431.     var appID = gApp.ID;
  7432.     // The default theme is always compatible.
  7433.     if (getResourceForID(id).EqualsNode(this._defaultTheme)) {
  7434.       var ver = gApp.version;
  7435.       return { appID: appID, minVersion: ver, maxVersion: ver };
  7436.     }
  7437.  
  7438.     var r = getResourceForID(id);
  7439.     var targetApps = datasource.GetTargets(r, EM_R("targetApplication"), true);
  7440.     if (!targetApps)
  7441.       return null;
  7442.  
  7443.     if (!targetApps.hasMoreElements())
  7444.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7445.     var outData = null;
  7446.     while (targetApps.hasMoreElements()) {
  7447.       var targetApp = targetApps.getNext();
  7448.       if (targetApp instanceof Ci.nsIRDFResource) {
  7449.         try {
  7450.           var foundAppID = stringData(datasource.GetTarget(targetApp, EM_R("id"), true));
  7451.           // Different target application?
  7452.           if (foundAppID != appID && foundAppID != TOOLKIT_ID)
  7453.             continue;
  7454.  
  7455.           outData = { appID: foundAppID,
  7456.                       minVersion: stringData(datasource.GetTarget(targetApp, EM_R("minVersion"), true)),
  7457.                       maxVersion: stringData(datasource.GetTarget(targetApp, EM_R("maxVersion"), true)) };
  7458.           if (foundAppID == appID)
  7459.             return outData;
  7460.         }
  7461.         catch (e) {
  7462.           continue;
  7463.         }
  7464.       }
  7465.     }
  7466.     return outData;
  7467.   },
  7468.  
  7469.   /**
  7470.    * Sets the target application info for an item in a datasource.
  7471.    * @param   id
  7472.    *          The GUID of the item to discover target application info for
  7473.    * @param   targetAppID
  7474.    *          The target application ID used for checking compatibility for this
  7475.    *          item.
  7476.    * @param   minVersion
  7477.    *          The minimum version of the target application that this item can
  7478.    *          run in
  7479.    * @param   maxVersion
  7480.    *          The maximum version of the target application that this item can
  7481.    *          run in
  7482.    * @param   datasource
  7483.    *          The datasource to look up target application info in
  7484.    *
  7485.    * @note Add-ons can specify a targetApplication id of toolkit@mozilla.org in
  7486.    *       their install manifest for compatibility with all apps using a
  7487.    *       specific release of the toolkit.
  7488.    */
  7489.   setTargetApplicationInfo: function(id, targetAppID, minVersion, maxVersion, datasource) {
  7490.     var targetDataSource = datasource;
  7491.     if (!targetDataSource)
  7492.       targetDataSource = this._inner;
  7493.  
  7494.     var appID = gApp.ID;
  7495.     var r = getResourceForID(id);
  7496.     var targetApps = targetDataSource.GetTargets(r, EM_R("targetApplication"), true);
  7497.     if (!targetApps.hasMoreElements())
  7498.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7499.     while (targetApps.hasMoreElements()) {
  7500.       var targetApp = targetApps.getNext();
  7501.       if (targetApp instanceof Ci.nsIRDFResource) {
  7502.         var foundAppID = stringData(targetDataSource.GetTarget(targetApp, EM_R("id"), true));
  7503.         // Different target application?
  7504.         if (foundAppID != targetAppID)
  7505.           continue;
  7506.  
  7507.         this._setProperty(targetDataSource, targetApp, EM_R("minVersion"), EM_L(minVersion));
  7508.         this._setProperty(targetDataSource, targetApp, EM_R("maxVersion"), EM_L(maxVersion));
  7509.  
  7510.         // If we were setting these properties on the main datasource, flush
  7511.         // it now. (Don't flush changes set on Install Manifests - they are
  7512.         // fleeting).
  7513.         if (!datasource)
  7514.           this.Flush();
  7515.  
  7516.         break;
  7517.       }
  7518.     }
  7519.   },
  7520.  
  7521.   /**
  7522.    * Gets a property of an item
  7523.    * @param   id
  7524.    *          The GUID of the item
  7525.    * @param   property
  7526.    *          The name of the property (excluding EM_NS)
  7527.    * @returns The literal value of the property, or undefined if there is no
  7528.    *          value.
  7529.    */
  7530.   getItemProperty: function(id, property) {
  7531.     var item = getResourceForID(id);
  7532.     if (!item) {
  7533.       LOG("getItemProperty failing for lack of an item. This means getResourceForItem \
  7534.            failed to locate a resource for aItemID (item ID = " + id + ", property = " + property + ")");
  7535.     }
  7536.     else
  7537.       return this._getItemProperty(item, property);
  7538.     return undefined;
  7539.   },
  7540.  
  7541.   /**
  7542.    * Gets a property of an item resource
  7543.    * @param   itemResource
  7544.    *          The RDF Resource of the item
  7545.    * @param   property
  7546.    *          The name of the property (excluding EM_NS)
  7547.    * @returns The literal value of the property, or undefined if there is no
  7548.    *          value.
  7549.    */
  7550.   _getItemProperty: function(itemResource, property) {
  7551.     var target = this.GetTarget(itemResource, EM_R(property), true);
  7552.     var value = stringData(target);
  7553.     if (value === undefined)
  7554.       value = intData(target);
  7555.     return value === undefined ? "" : value;
  7556.   },
  7557.  
  7558.   /**
  7559.    * Sets a property on an item.
  7560.    * @param   id
  7561.    *          The GUID of the item
  7562.    * @param   propertyArc
  7563.    *          The RDF Resource of the property arc
  7564.    * @param   propertyValue
  7565.    *          A nsIRDFLiteral value of the property to be set
  7566.    */
  7567.   setItemProperty: function (id, propertyArc, propertyValue) {
  7568.     var item = getResourceForID(id);
  7569.     this._setProperty(this._inner, item, propertyArc, propertyValue);
  7570.     this.Flush();
  7571.   },
  7572.  
  7573.   /**
  7574.    * Sets one or more properties for an item.
  7575.    * @param   id
  7576.    *          The ID of the item
  7577.    * @param   properties
  7578.    *          A JS object which maps properties to values.
  7579.    */
  7580.   setItemProperties: function (id, properties) {
  7581.     var item = getResourceForID(id);
  7582.     for (var key in properties)
  7583.       this._setProperty(this._inner, item, EM_R(key), properties[key]);
  7584.     this.Flush();
  7585.   },
  7586.  
  7587.   /**
  7588.    * Inserts the RDF resource for an item into a container.
  7589.    * @param   id
  7590.    *          The GUID of the item
  7591.    */
  7592.   insertItemIntoContainer: function(id) {
  7593.     // Get the target container and resource
  7594.     var ctr = getContainer(this._inner, this._itemRoot);
  7595.     var itemResource = getResourceForID(id);
  7596.     // Don't bother adding the extension to the list if it's already there.
  7597.     // (i.e. we're upgrading)
  7598.     var oldIndex = ctr.IndexOf(itemResource);
  7599.     if (oldIndex == -1)
  7600.       ctr.AppendElement(itemResource);
  7601.     this.Flush();
  7602.   },
  7603.  
  7604.   /**
  7605.    * Removes the RDF resource for an item from its container.
  7606.    * @param   id
  7607.    *          The GUID of the item
  7608.    */
  7609.   removeItemFromContainer: function(id) {
  7610.     var ctr = getContainer(this._inner, this._itemRoot);
  7611.     var itemResource = getResourceForID(id);
  7612.     ctr.RemoveElement(itemResource, true);
  7613.     this.Flush();
  7614.   },
  7615.  
  7616.   /**
  7617.    * Removes a corrupt item entry from the extension list added due to buggy
  7618.    * code in previous EM versions!
  7619.    * @param   id
  7620.    *          The GUID of the item
  7621.    */
  7622.   removeCorruptItem: function(id) {
  7623.     this.removeItemMetadata(id);
  7624.     this.removeItemFromContainer(id);
  7625.     this.visibleItems[id] = null;
  7626.   },
  7627.  
  7628.   /**
  7629.    * Removes a corrupt download entry from the list
  7630.    * @param   uri
  7631.    *          The RDF URI of the item.
  7632.    * @returns The RDF Resource of the removed entry
  7633.    */
  7634.   removeCorruptDLItem: function(uri) {
  7635.     var itemResource = gRDF.GetResource(uri);
  7636.     var ctr = getContainer(this._inner, this._itemRoot);
  7637.     if (ctr.IndexOf(itemResource) != -1) {
  7638.       ctr.RemoveElement(itemResource, true);
  7639.       this._cleanResource(itemResource);
  7640.       this.Flush();
  7641.     }
  7642.     return itemResource;
  7643.   },
  7644.  
  7645.   /**
  7646.    * Copies localized properties from an install manifest to the datasource
  7647.    *
  7648.    * @param   installManifest
  7649.    *          The Install Manifest datasource we are copying from
  7650.    * @param   source
  7651.    *          The source resource of the localized properties
  7652.    * @param   target
  7653.    *          The target resource to store the localized properties
  7654.    */
  7655.   _addLocalizedMetadata: function(installManifest, sourceRes, targetRes)
  7656.   {
  7657.     var singleProps = ["name", "description", "creator", "homepageURL"];
  7658.  
  7659.     for (var i = 0; i < singleProps.length; ++i) {
  7660.       var property = EM_R(singleProps[i]);
  7661.       var literal = installManifest.GetTarget(sourceRes, property, true);
  7662.       // If literal is null, _setProperty will remove any existing.
  7663.       this._setProperty(this._inner, targetRes, property, literal);
  7664.     }
  7665.  
  7666.     // Assert properties with multiple values
  7667.     var manyProps = ["developer", "translator", "contributor"];
  7668.     for (var i = 0; i < manyProps.length; ++i) {
  7669.       var property = EM_R(manyProps[i]);
  7670.       var literals = installManifest.GetTargets(sourceRes, property, true);
  7671.  
  7672.       var oldValues = this._inner.GetTargets(targetRes, property, true);
  7673.       while (oldValues.hasMoreElements()) {
  7674.         var oldValue = oldValues.getNext().QueryInterface(Ci.nsIRDFNode);
  7675.         this._inner.Unassert(targetRes, property, oldValue);
  7676.       }
  7677.       while (literals.hasMoreElements()) {
  7678.         var literal = literals.getNext().QueryInterface(Ci.nsIRDFNode);
  7679.         this._inner.Assert(targetRes, property, literal, true);
  7680.       }
  7681.     }
  7682.  
  7683.   },
  7684.  
  7685.   /**
  7686.    * Copies metadata from an Install Manifest Datasource into the Extensions
  7687.    * DataSource.
  7688.    * @param   id
  7689.    *          The GUID of the item
  7690.    * @param   installManifest
  7691.    *          The Install Manifest datasource we are copying from
  7692.    * @param   installLocation
  7693.    *          The Install Location of the item.
  7694.    */
  7695.   addItemMetadata: function(id, installManifest, installLocation) {
  7696.     var targetRes = getResourceForID(id);
  7697.     // Remove any temporary assertions used for the install process
  7698.     this._setProperty(this._inner, targetRes, EM_R("newVersion"), null);
  7699.     // Copy the assertions over from the source datasource.
  7700.     // Assert properties with single values
  7701.     var singleProps = ["version", "updateURL", "updateService", "optionsURL",
  7702.                        "aboutURL", "iconURL", "internalName", "updateKey"];
  7703.  
  7704.     // Items installed into restricted Install Locations can also be locked
  7705.     // (can't be removed or disabled), and hidden (not shown in the UI)
  7706.     if (installLocation.restricted)
  7707.       singleProps = singleProps.concat(["locked", "hidden"]);
  7708.     if (installLocation.name == KEY_APP_GLOBAL)
  7709.       singleProps = singleProps.concat(["appManaged"]);
  7710.     for (var i = 0; i < singleProps.length; ++i) {
  7711.       var property = EM_R(singleProps[i]);
  7712.       var literal = installManifest.GetTarget(gInstallManifestRoot, property, true);
  7713.       // If literal is null, _setProperty will remove any existing.
  7714.       this._setProperty(this._inner, targetRes, property, literal);
  7715.     }
  7716.  
  7717.     var localizedProp = EM_R("localized");
  7718.     var localeProp = EM_R("locale");
  7719.     // Remove old localized properties
  7720.     var oldValues = this._inner.GetTargets(targetRes, localizedProp, true);
  7721.     while (oldValues.hasMoreElements()) {
  7722.       var oldValue = oldValues.getNext().QueryInterface(Ci.nsIRDFNode);
  7723.       this._cleanResource(oldValue);
  7724.       this._inner.Unassert(targetRes, localizedProp, oldValue);
  7725.     }
  7726.     // Add each localized property
  7727.     var localizations = installManifest.GetTargets(gInstallManifestRoot, localizedProp, true);
  7728.     while (localizations.hasMoreElements()) {
  7729.       var localization = localizations.getNext().QueryInterface(Ci.nsIRDFResource);
  7730.       var anon = gRDF.GetAnonymousResource();
  7731.       var literals = installManifest.GetTargets(localization, localeProp, true);
  7732.       while (literals.hasMoreElements()) {
  7733.         var literal = literals.getNext().QueryInterface(Ci.nsIRDFNode);
  7734.         this._inner.Assert(anon, localeProp, literal, true);
  7735.       }
  7736.       this._addLocalizedMetadata(installManifest, localization, anon);
  7737.       this._inner.Assert(targetRes, localizedProp, anon, true);
  7738.     }
  7739.     // Add the fallback properties
  7740.     this._addLocalizedMetadata(installManifest, gInstallManifestRoot, targetRes);
  7741.  
  7742.     // Version/Dependency Info
  7743.     var versionProps = ["targetApplication", "requires"];
  7744.     var idRes = EM_R("id");
  7745.     var minVersionRes = EM_R("minVersion");
  7746.     var maxVersionRes = EM_R("maxVersion");
  7747.     for (var i = 0; i < versionProps.length; ++i) {
  7748.       var property = EM_R(versionProps[i]);
  7749.       var newVersionInfos = installManifest.GetTargets(gInstallManifestRoot, property, true);
  7750.  
  7751.       var oldVersionInfos = this._inner.GetTargets(targetRes, property, true);
  7752.       while (oldVersionInfos.hasMoreElements()) {
  7753.         var oldVersionInfo = oldVersionInfos.getNext().QueryInterface(Ci.nsIRDFResource);
  7754.         this._cleanResource(oldVersionInfo);
  7755.         this._inner.Unassert(targetRes, property, oldVersionInfo);
  7756.       }
  7757.       while (newVersionInfos.hasMoreElements()) {
  7758.         var newVersionInfo = newVersionInfos.getNext().QueryInterface(Ci.nsIRDFResource);
  7759.         var anon = gRDF.GetAnonymousResource();
  7760.         this._inner.Assert(anon, idRes, installManifest.GetTarget(newVersionInfo, idRes, true), true);
  7761.         this._inner.Assert(anon, minVersionRes, installManifest.GetTarget(newVersionInfo, minVersionRes, true), true);
  7762.         this._inner.Assert(anon, maxVersionRes, installManifest.GetTarget(newVersionInfo, maxVersionRes, true), true);
  7763.         this._inner.Assert(targetRes, property, anon, true);
  7764.       }
  7765.     }
  7766.     this.updateProperty(id, "opType");
  7767.     this.updateProperty(id, "updateable");
  7768.     this.Flush();
  7769.   },
  7770.  
  7771.   /**
  7772.    * Strips an item entry of all assertions.
  7773.    * @param   id
  7774.    *          The GUID of the item
  7775.    */
  7776.   removeItemMetadata: function(id) {
  7777.     var item = getResourceForID(id);
  7778.     var resources = ["targetApplication", "requires", "localized"];
  7779.     for (var i = 0; i < resources.length; ++i) {
  7780.       var targetApps = this._inner.GetTargets(item, EM_R(resources[i]), true);
  7781.       while (targetApps.hasMoreElements()) {
  7782.         var targetApp = targetApps.getNext().QueryInterface(Ci.nsIRDFResource);
  7783.         this._cleanResource(targetApp);
  7784.       }
  7785.     }
  7786.  
  7787.     this._cleanResource(item);
  7788.   },
  7789.  
  7790.   /**
  7791.    * Strips a resource of all outbound assertions. We use methods like this
  7792.    * since the RDFXMLDatasource will write out all assertions, even if they
  7793.    * are not connected through our root.
  7794.    * @param   resource
  7795.    *          The resource to clean.
  7796.    */
  7797.   _cleanResource: function(resource) {
  7798.     // Remove outward arcs
  7799.     var arcs = this._inner.ArcLabelsOut(resource);
  7800.     while (arcs.hasMoreElements()) {
  7801.       var arc = arcs.getNext().QueryInterface(Ci.nsIRDFResource);
  7802.       var targets = this._inner.GetTargets(resource, arc, true);
  7803.       while (targets.hasMoreElements()) {
  7804.         var value = targets.getNext().QueryInterface(Ci.nsIRDFNode);
  7805.         if (value)
  7806.           this._inner.Unassert(resource, arc, value);
  7807.       }
  7808.     }
  7809.   },
  7810.  
  7811.   /**
  7812.    * Notify views that this propery has changed (this is for properties that
  7813.    * are implemented by this datasource rather than by the inner in-memory
  7814.    * datasource and thus do not get free change handling).
  7815.    * @param   id
  7816.    *          The GUID of the item to update the property for.
  7817.    * @param   property
  7818.    *          The property (less EM_NS) to update.
  7819.    */
  7820.   updateProperty: function(id, property) {
  7821.     var item = getResourceForID(id);
  7822.     this._updateProperty(item, property);
  7823.   },
  7824.  
  7825.   /**
  7826.    * Notify views that this propery has changed (this is for properties that
  7827.    * are implemented by this datasource rather than by the inner in-memory
  7828.    * datasource and thus do not get free change handling). This allows updating
  7829.    * properties for download items which don't have the em item prefix in there
  7830.    ( resource value. In most instances updateProperty should be used.
  7831.    * @param   item
  7832.    *          The item to update the property for.
  7833.    * @param   property
  7834.    *          The property (less EM_NS) to update.
  7835.    */
  7836.   _updateProperty: function(item, property) {
  7837.     if (item) {
  7838.       var propertyResource = EM_R(property);
  7839.       var value = this.GetTarget(item, propertyResource, true);
  7840.       for (var i = 0; i < this._observers.length; ++i) {
  7841.         if (value)
  7842.           this._observers[i].onChange(this, item, propertyResource,
  7843.                                       EM_L(""), value);
  7844.         else
  7845.           this._observers[i].onUnassert(this, item, propertyResource,
  7846.                                         EM_L(""));
  7847.       }
  7848.     }
  7849.   },
  7850.  
  7851.   /**
  7852.    * Move an Item to the index of another item in its container.
  7853.    * @param   movingID
  7854.    *          The ID of the item to be moved.
  7855.    * @param   destinationID
  7856.    *          The ID of an item to move another item to.
  7857.    */
  7858.   moveToIndexOf: function(movingID, destinationID) {
  7859.     var extensions = gRDF.GetResource(RDFURI_ITEM_ROOT);
  7860.     var ctr = getContainer(this._inner, extensions);
  7861.     var item = gRDF.GetResource(movingID);
  7862.     var index = ctr.IndexOf(gRDF.GetResource(destinationID));
  7863.     if (index == -1)
  7864.       index = 1; // move to the beginning if destinationID is not found
  7865.     this._inner.beginUpdateBatch();
  7866.     ctr.RemoveElement(item, true);
  7867.     ctr.InsertElementAt(item, index, true);
  7868.     this._inner.endUpdateBatch();
  7869.     this.Flush();
  7870.   },
  7871.  
  7872.   /**
  7873.    * Sorts addons of the specified type by the specified property starting from
  7874.    * the top of their container. If the addons are already sorted then no action
  7875.    * is performed.
  7876.    * @param   type
  7877.    *          The nsIUpdateItem type of the items to sort.
  7878.    * @param   propertyName
  7879.    *          The RDF property name used for sorting.
  7880.    * @param   isAscending
  7881.    *          true to sort ascending and false to sort descending
  7882.    */
  7883.   sortTypeByProperty: function(type, propertyName, isAscending) {
  7884.     var items = [];
  7885.     var ctr = getContainer(this._inner, this._itemRoot);
  7886.     var elements = ctr.GetElements();
  7887.     // Base 0 ordinal for checking against the existing order after sorting
  7888.     var ordinal = 0;
  7889.     while (elements.hasMoreElements()) {
  7890.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7891.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7892.       var itemType = this.getItemProperty(id, "type");
  7893.       if (itemType & type) {
  7894.         items.push({ item   : item,
  7895.                      ordinal: ordinal,
  7896.                      sortkey: this.getItemProperty(id, propertyName).toLowerCase() });
  7897.         ordinal++;
  7898.       }
  7899.     }
  7900.  
  7901.     var direction = isAscending ? 1 : -1;
  7902.     // Case insensitive sort
  7903.     function compare(a, b) {
  7904.         if (a.sortkey < b.sortkey) return (-1 * direction);
  7905.         if (a.sortkey > b.sortkey) return (1 * direction);
  7906.         return 0;
  7907.     }
  7908.     items.sort(compare);
  7909.  
  7910.     // Check if there are any changes in the order of the items
  7911.     var isDirty = false;
  7912.     for (var i = 0; i < items.length; i++) {
  7913.       if (items[i].ordinal != i) {
  7914.         isDirty = true;
  7915.         break;
  7916.       }
  7917.     }
  7918.  
  7919.     // If there are no changes then early return to avoid the perf impact
  7920.     if (!isDirty)
  7921.       return;
  7922.  
  7923.     // Reorder the items by moving them to the top of the container
  7924.     this.beginUpdateBatch();
  7925.     for (i = 0; i < items.length; i++) {
  7926.       ctr.RemoveElement(items[i].item, true);
  7927.       ctr.InsertElementAt(items[i].item, i + 1, true);
  7928.     }
  7929.     this.endUpdateBatch();
  7930.     this.Flush();
  7931.   },
  7932.  
  7933.   /**
  7934.    * Determines if an Item is an active download
  7935.    * @param   id
  7936.    *          The ID of the item. This will be a uri scheme without the
  7937.    *          em item prefix so getProperty shouldn't be used.
  7938.    * @returns true if the item is an active download, false otherwise.
  7939.    */
  7940.   isDownloadItem: function(id) {
  7941.     var downloadURL = stringData(this.GetTarget(gRDF.GetResource(id), EM_R("downloadURL"), true));
  7942.     return downloadURL && downloadURL != "";
  7943.   },
  7944.  
  7945.   /**
  7946.    * Adds an entry representing an active download to the appropriate container
  7947.    * @param   addon
  7948.    *          An object implementing nsIUpdateItem for the addon being
  7949.    *          downloaded.
  7950.    */
  7951.   addDownload: function(addon) {
  7952.     // Updates have already been added to the datasource so we just update the
  7953.     // download state.
  7954.     if (addon.id != addon.xpiURL) {
  7955.       this.updateDownloadState(PREFIX_ITEM_URI + addon.id, "waiting");
  7956.       return;
  7957.     }
  7958.     var res = gRDF.GetResource(addon.xpiURL);
  7959.     this._setProperty(this._inner, res, EM_R("name"), EM_L(addon.name));
  7960.     this._setProperty(this._inner, res, EM_R("version"), EM_L(addon.version));
  7961.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(addon.iconURL));
  7962.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(addon.xpiURL));
  7963.     this._setProperty(this._inner, res, EM_R("type"), EM_I(addon.type));
  7964.  
  7965.     var ctr = getContainer(this._inner, this._itemRoot);
  7966.     if (ctr.IndexOf(res) == -1)
  7967.       ctr.AppendElement(res);
  7968.  
  7969.     this.updateDownloadState(addon.xpiURL, "waiting");
  7970.     this.Flush();
  7971.   },
  7972.  
  7973.   /**
  7974.    * Adds an entry representing an item that is incompatible and is being
  7975.    * checked for a compatibility update.
  7976.    * @param   name
  7977.    *          The display name of the item being checked
  7978.    * @param   url
  7979.    *          The URL string of the xpi file that has been staged.
  7980.    * @param   type
  7981.    *          The nsIUpdateItem type of the item
  7982.    * @param   version
  7983.    *          The version of the item
  7984.    */
  7985.   addIncompatibleUpdateItem: function(name, url, type, version) {
  7986.     var iconURL = (type == Ci.nsIUpdateItem.TYPE_THEME) ? URI_GENERIC_ICON_THEME :
  7987.                                                           URI_GENERIC_ICON_XPINSTALL;
  7988.     var extensionsStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  7989.     var updateMsg = extensionsStrings.formatStringFromName("incompatibleUpdateMessage",
  7990.                                                            [BundleManager.appName, name], 2)
  7991.  
  7992.     var res = gRDF.GetResource(url);
  7993.     this._setProperty(this._inner, res, EM_R("name"), EM_L(name));
  7994.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(iconURL));
  7995.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(url));
  7996.     this._setProperty(this._inner, res, EM_R("type"), EM_I(type));
  7997.     this._setProperty(this._inner, res, EM_R("version"), EM_L(version));
  7998.     this._setProperty(this._inner, res, EM_R("incompatibleUpdate"), EM_L("true"));
  7999.     this._setProperty(this._inner, res, EM_R("description"), EM_L(updateMsg));
  8000.  
  8001.     var ctr = getContainer(this._inner, this._itemRoot);
  8002.     if (ctr.IndexOf(res) == -1)
  8003.       ctr.AppendElement(res);
  8004.  
  8005.     this.updateDownloadState(url, "incompatibleUpdate");
  8006.     this.Flush();
  8007.   },
  8008.  
  8009.   /**
  8010.    * Removes an active download from the appropriate container
  8011.    * @param   url
  8012.    *          The URL string of the active download to be removed
  8013.    */
  8014.   removeDownload: function(url) {
  8015.     var res = gRDF.GetResource(url);
  8016.     var ctr = getContainer(this._inner, this._itemRoot);
  8017.     if (ctr.IndexOf(res) != -1)
  8018.       ctr.RemoveElement(res, true);
  8019.     this._cleanResource(res);
  8020.     this.updateDownloadState(url, null);
  8021.     this.Flush();
  8022.   },
  8023.  
  8024.   /**
  8025.    * A hash of RDF resource values (e.g. Add-on IDs or XPI URLs) that represent
  8026.    * installation progress for a single browser session.
  8027.    */
  8028.   _progressData: { },
  8029.  
  8030.   /**
  8031.    * Updates the install progress data for a given ID (e.g. Add-on IDs or
  8032.    * XPI URLs).
  8033.    * @param   id
  8034.    *          The URL string of the active download to be removed
  8035.    * @param   state
  8036.    *          The current state in the installation process. If null the object
  8037.    *          is deleted from _progressData.
  8038.    */
  8039.   updateDownloadState: function(id, state) {
  8040.     if (!state) {
  8041.       if (id in this._progressData)
  8042.         delete this._progressData[id];
  8043.       return;
  8044.     }
  8045.     else {
  8046.       if (!(id in this._progressData))
  8047.         this._progressData[id] = { };
  8048.       this._progressData[id].state = state;
  8049.     }
  8050.     var item = gRDF.GetResource(id);
  8051.     this._updateProperty(item, "state");
  8052.   },
  8053.  
  8054.   updateDownloadProgress: function(id, progress) {
  8055.     if (!progress) {
  8056.       if (!(id in this._progressData))
  8057.         return;
  8058.       this._progressData[id].progress = null;
  8059.     }
  8060.     else {
  8061.       if (!(id in this._progressData))
  8062.         this.updateDownloadState(id, "downloading");
  8063.  
  8064.       if (this._progressData[id].progress == progress)
  8065.         return;
  8066.  
  8067.       this._progressData[id].progress = progress;
  8068.     }
  8069.     var item = gRDF.GetResource(id);
  8070.     this._updateProperty(item, "progress");
  8071.   },
  8072.  
  8073.   /**
  8074.    * A GUID->location-key hash of items that are visible to the application.
  8075.    * These are items that show up in the Extension/Themes etc UI. If there is
  8076.    * an instance of the same item installed in Install Locations of differing
  8077.    * profiles, the item at the highest priority location will appear in this
  8078.    * list.
  8079.    */
  8080.   visibleItems: { },
  8081.  
  8082.   /**
  8083.    * Walk the list of installed items and determine what the visible list is,
  8084.    * based on which items are visible at the highest priority locations.
  8085.    */
  8086.   _buildVisibleItemList: function() {
  8087.     var ctr = getContainer(this, this._itemRoot);
  8088.     var items = ctr.GetElements();
  8089.     while (items.hasMoreElements()) {
  8090.       var item = items.getNext().QueryInterface(Ci.nsIRDFResource);
  8091.       // Resource URIs adopt the format: location-key,item-id
  8092.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8093.       this.visibleItems[id] = this.getItemProperty(id, "installLocation");
  8094.     }
  8095.   },
  8096.  
  8097.   /**
  8098.    * Updates an item's location in the visible item list.
  8099.    * @param   id
  8100.    *          The GUID of the item to update
  8101.    * @param   locationKey
  8102.    *          The name of the Install Location where the item is installed.
  8103.    * @param   forceReplace
  8104.    *          true if the new location should be used, regardless of its
  8105.    *          priority relationship to existing entries, false if the location
  8106.    *          should only be updated if its priority is lower than the existing
  8107.    *          value.
  8108.    */
  8109.   updateVisibleList: function(id, locationKey, forceReplace) {
  8110.     if (id in this.visibleItems && this.visibleItems[id]) {
  8111.       var oldLocation = InstallLocations.get(this.visibleItems[id]);
  8112.       var newLocation = InstallLocations.get(locationKey);
  8113.       if (forceReplace || !oldLocation || newLocation.priority < oldLocation.priority)
  8114.         this.visibleItems[id] = locationKey;
  8115.     }
  8116.     else
  8117.       this.visibleItems[id] = locationKey;
  8118.   },
  8119.  
  8120.   /**
  8121.    * Load the Extensions Datasource from disk.
  8122.    */
  8123.   loadExtensions: function() {
  8124.     var extensionsFile  = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  8125.     try {
  8126.       this._inner = gRDF.GetDataSourceBlocking(getURLSpecFromFile(extensionsFile));
  8127.     }
  8128.     catch (e) {
  8129.       ERROR("Datasource::loadExtensions: removing corrupted extensions datasource " +
  8130.             " file = " + extensionsFile.path + ", exception = " + e + "\n");
  8131.       extensionsFile.remove(false);
  8132.       return;
  8133.     }
  8134.  
  8135.     var cu = Cc["@mozilla.org/rdf/container-utils;1"].
  8136.              getService(Ci.nsIRDFContainerUtils);
  8137.     cu.MakeSeq(this._inner, this._itemRoot);
  8138.  
  8139.     this._buildVisibleItemList();
  8140.   },
  8141.  
  8142.   /**
  8143.    * See nsIExtensionManager.idl
  8144.    */
  8145.   onUpdateStarted: function() {
  8146.     LOG("Datasource: Update Started");
  8147.   },
  8148.  
  8149.   /**
  8150.    * See nsIExtensionManager.idl
  8151.    */
  8152.   onUpdateEnded: function() {
  8153.     LOG("Datasource: Update Ended");
  8154.   },
  8155.  
  8156.   /**
  8157.    * See nsIExtensionManager.idl
  8158.    */
  8159.   onAddonUpdateStarted: function(addon) {
  8160.     if (!addon)
  8161.       throw Cr.NS_ERROR_INVALID_ARG;
  8162.  
  8163.     LOG("Datasource: Addon Update Started: " + addon.id);
  8164.     this.updateProperty(addon.id, "availableUpdateURL");
  8165.   },
  8166.  
  8167.   /**
  8168.    * See nsIExtensionManager.idl
  8169.    */
  8170.   onAddonUpdateEnded: function(addon, status) {
  8171.     if (!addon)
  8172.       throw Cr.NS_ERROR_INVALID_ARG;
  8173.  
  8174.     LOG("Datasource: Addon Update Ended: " + addon.id + ", status: " + status);
  8175.     var url = null, hash = null, version = null;
  8176.     var updateAvailable = status == Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE;
  8177.     if (updateAvailable) {
  8178.       url = EM_L(addon.xpiURL);
  8179.       if (addon.xpiHash)
  8180.         hash = EM_L(addon.xpiHash);
  8181.       version = EM_L(addon.version);
  8182.     }
  8183.     this.setItemProperties(addon.id, {
  8184.       availableUpdateURL: url,
  8185.       availableUpdateHash: hash,
  8186.       availableUpdateVersion: version
  8187.     });
  8188.     this.updateProperty(addon.id, "availableUpdateURL");
  8189.   },
  8190.  
  8191.   /////////////////////////////////////////////////////////////////////////////
  8192.   // nsIRDFDataSource
  8193.   get URI() {
  8194.     return "rdf:extensions";
  8195.   },
  8196.  
  8197.   GetSource: function(property, target, truthValue) {
  8198.     return this._inner.GetSource(property, target, truthValue);
  8199.   },
  8200.  
  8201.   GetSources: function(property, target, truthValue) {
  8202.     return this._inner.GetSources(property, target, truthValue);
  8203.   },
  8204.  
  8205.   /**
  8206.    * Gets an URL to a theme's image file
  8207.    * @param   item
  8208.    *          The RDF Resource representing the item
  8209.    * @param   fileName
  8210.    *          The file to locate a URL for
  8211.    * @param   fallbackURL
  8212.    *          If the location fails, supply this URL instead
  8213.    * @returns An RDF Resource to the URL discovered, or the fallback
  8214.    *          if the discovery failed.
  8215.    */
  8216.   _getThemeImageURL: function(item, fileName, fallbackURL) {
  8217.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8218.     var installLocation = this._em.getInstallLocation(id);
  8219.     if (!installLocation)
  8220.       return fallbackURL;
  8221.     var file = installLocation.getItemFile(id, fileName)
  8222.     if (file.exists())
  8223.       return gRDF.GetResource(getURLSpecFromFile(file));
  8224.  
  8225.     if (id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)) {
  8226.       var jarFile = getFile(KEY_APPDIR, [DIR_CHROME, FILE_DEFAULT_THEME_JAR]);
  8227.       var url = "jar:" + getURLSpecFromFile(jarFile) + "!/" + fileName;
  8228.       return gRDF.GetResource(url);
  8229.     }
  8230.  
  8231.     return fallbackURL ? gRDF.GetResource(fallbackURL) : null;
  8232.   },
  8233.  
  8234.   /**
  8235.    * Get the em:iconURL property (icon url of the item)
  8236.    */
  8237.   _rdfGet_iconURL: function(item, property) {
  8238.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8239.     var type = this.getItemProperty(id, "type");
  8240.     if (type & Ci.nsIUpdateItem.TYPE_THEME)
  8241.       return this._getThemeImageURL(item, "icon.png", URI_GENERIC_ICON_THEME);
  8242.  
  8243.     if (inSafeMode())
  8244.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8245.  
  8246.     var hasIconURL = this._inner.hasArcOut(item, property);
  8247.     // If the addon doesn't have an IconURL property or it is disabled use the
  8248.     // generic icon URL instead.
  8249.     if (!hasIconURL || this.getItemProperty(id, "isDisabled") == "true")
  8250.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8251.     var iconURL = stringData(this._inner.GetTarget(item, property, true));
  8252.     try {
  8253.       var uri = newURI(iconURL);
  8254.       var scheme = uri.scheme;
  8255.       // Only allow chrome URIs or when installing http(s) URIs.
  8256.       if (scheme == "chrome" || (scheme == "http" || scheme == "https") &&
  8257.           this._inner.hasArcOut(item, EM_R("downloadURL")))
  8258.         return null;
  8259.     }
  8260.     catch (e) {
  8261.     }
  8262.     // Use a generic icon URL for addons that have an invalid iconURL.
  8263.     return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8264.   },
  8265.  
  8266.   /**
  8267.    * Get the em:previewImage property (preview image of the item)
  8268.    */
  8269.   _rdfGet_previewImage: function(item, property) {
  8270.     var type = this.getItemProperty(stripPrefix(item.Value, PREFIX_ITEM_URI), "type");
  8271.     if (type != -1 && type & Ci.nsIUpdateItem.TYPE_THEME)
  8272.       return this._getThemeImageURL(item, "preview.png", null);
  8273.     return null;
  8274.   },
  8275.  
  8276.   /**
  8277.    * If we're in safe mode, the item is disabled by the user or app, or the
  8278.    * item is to be upgraded force the generic about dialog for the item.
  8279.    */
  8280.   _rdfGet_aboutURL: function(item, property) {
  8281.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8282.     if (inSafeMode() || this.getItemProperty(id, "isDisabled") == "true" ||
  8283.         this.getItemProperty(id, "opType") == OP_NEEDS_UPGRADE)
  8284.       return EM_L("");
  8285.  
  8286.     return null;
  8287.   },
  8288.  
  8289.   _rdfGet_installDate: function(item, property) {
  8290.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8291.     var key = this.getItemProperty(id, "installLocation");
  8292.     if (key && key in StartupCache.entries && id in StartupCache.entries[key] &&
  8293.         StartupCache.entries[key][id] && StartupCache.entries[key][id].mtime)
  8294.       return EM_D(StartupCache.entries[key][id].mtime * 1000000);
  8295.     return null;
  8296.   },
  8297.  
  8298.   /**
  8299.    * Get the em:compatible property (whether or not this item is compatible)
  8300.    */
  8301.   _rdfGet_compatible: function(item, property) {
  8302.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8303.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  8304.     if (!targetAppInfo) {
  8305.       // When installing a new addon targetAppInfo does not exist yet
  8306.       if (this.getItemProperty(id, "opType") == OP_NEEDS_INSTALL)
  8307.         return EM_L("true");
  8308.       return EM_L("false");
  8309.     }
  8310.  
  8311.     getVersionChecker();
  8312.     var appVersion = targetAppInfo.appID == TOOLKIT_ID ? gApp.platformVersion : gApp.version;
  8313.     if (gVersionChecker.compare(targetAppInfo.maxVersion, appVersion) < 0 ||
  8314.         gVersionChecker.compare(appVersion, targetAppInfo.minVersion) < 0) {
  8315.       // OK, this item is incompatible.
  8316.       return EM_L("false");
  8317.     }
  8318.     return EM_L("true");
  8319.   },
  8320.  
  8321.   /**
  8322.    * Get the providesUpdatesSecurely property (whether or not this item has a
  8323.    * secure update mechanism)
  8324.    */
  8325.   _rdfGet_providesUpdatesSecurely: function(item, property) {
  8326.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8327.     if (this.getItemProperty(id, "updateKey") ||
  8328.         !this.getItemProperty(id, "updateURL") ||
  8329.         this.getItemProperty(id, "updateURL").substring(0, 6) == "https:")
  8330.       return EM_L("true");
  8331.     return EM_L("false");
  8332.   },
  8333.  
  8334.   /**
  8335.    * Get the em:blocklisted property (whether or not this item is blocklisted)
  8336.    */
  8337.   _rdfGet_blocklisted: function(item, property) {
  8338.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8339.     var version = this.getItemProperty(id, "version");
  8340.     if (!gBlocklist)
  8341.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  8342.                    getService(Ci.nsIBlocklistService);
  8343.     if (gBlocklist.isAddonBlocklisted(id, version, null, null))
  8344.       return EM_L("true");
  8345.  
  8346.     return EM_L("false");
  8347.   },
  8348.  
  8349.   /**
  8350.    * Get the em:state property (represents the current phase of an install).
  8351.    */
  8352.   _rdfGet_state: function(item, property) {
  8353.     var id = item.Value;
  8354.     if (id in this._progressData)
  8355.       return EM_L(this._progressData[id].state);
  8356.     return null;
  8357.   },
  8358.  
  8359.   /**
  8360.    * Get the em:progress property from the _progressData js object. By storing
  8361.    * progress which is updated repeastedly during a download we avoid
  8362.    * repeastedly writing it to the rdf file.
  8363.    */
  8364.   _rdfGet_progress: function(item, property) {
  8365.     var id = item.Value;
  8366.     if (id in this._progressData)
  8367.       return EM_I(this._progressData[id].progress);
  8368.     return null;
  8369.   },
  8370.  
  8371.   /**
  8372.    * Get the em:appManaged property. This prevents extensions from hiding
  8373.    * extensions installed into locations other than the app-global location.
  8374.    */
  8375.   _rdfGet_appManaged: function(item, property) {
  8376.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8377.     var locationKey = this.getItemProperty(id, "installLocation");
  8378.     if (locationKey != KEY_APP_GLOBAL)
  8379.       return EM_L("false");
  8380.     return null;
  8381.   },
  8382.  
  8383.   /**
  8384.    * Get the em:hidden property. This prevents extensions from hiding
  8385.    * extensions installed into locations other than restricted locations.
  8386.    */
  8387.   _rdfGet_hidden: function(item, property) {
  8388.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8389.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8390.     if (!installLocation || !installLocation.restricted)
  8391.       return EM_L("false");
  8392.     return null;
  8393.   },
  8394.  
  8395.   /**
  8396.    * Get the em:locked property. This prevents extensions from locking
  8397.    * extensions installed into locations other than restricted locations.
  8398.    */
  8399.   _rdfGet_locked: function(item, property) {
  8400.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8401.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8402.     if (!installLocation || !installLocation.restricted)
  8403.       return EM_L("false");
  8404.     return null;
  8405.   },
  8406.  
  8407.   /**
  8408.    * Get the em:satisfiesDependencies property - literal string "false" for
  8409.    * dependencies not satisfied (e.g. dependency disabled, incorrect version,
  8410.    * not installed etc.), and literal string "true" for dependencies satisfied.
  8411.    */
  8412.   _rdfGet_satisfiesDependencies: function(item, property) {
  8413.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8414.     if (this.satisfiesDependencies(id))
  8415.       return EM_L("true");
  8416.     return EM_L("false");
  8417.   },
  8418.  
  8419.   /**
  8420.    * Get the em:opType property (controls widget state for the EM UI)
  8421.    * from the Startup Cache (e.g. extensions.cache)
  8422.    */
  8423.   _rdfGet_opType: function(item, property) {
  8424.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8425.     var key = this.getItemProperty(id, "installLocation");
  8426.     if (key in StartupCache.entries && id in StartupCache.entries[key] &&
  8427.         StartupCache.entries[key][id] && StartupCache.entries[key][id].op != OP_NONE)
  8428.       return EM_L(StartupCache.entries[key][id].op);
  8429.     return null;
  8430.   },
  8431.  
  8432.   /**
  8433.    * Gets a localizable property. Install Manifests are generally only in one
  8434.    * language, however an item can customize by providing localized prefs in
  8435.    * the form:
  8436.    *
  8437.    *    extensions.{GUID}.[name|description|creator|homepageURL]
  8438.    *
  8439.    * to specify localized text for each of these properties.
  8440.    */
  8441.   _getLocalizablePropertyValue: function(item, property) {
  8442.     // These are localizable properties that a language pack supplied by the
  8443.     // Extension may override.
  8444.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/,
  8445.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) +
  8446.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8447.     try {
  8448.       var value = gPref.getComplexValue(prefName,
  8449.                                         Ci.nsIPrefLocalizedString);
  8450.       if (value.data)
  8451.         return EM_L(value.data);
  8452.     }
  8453.     catch (e) {
  8454.     }
  8455.  
  8456.     var localized = findClosestLocalizedResource(this._inner, item);
  8457.     if (localized) {
  8458.       var value = this._inner.GetTarget(localized, property, true);
  8459.       return value ? value : EM_L("");
  8460.     }
  8461.     return null;
  8462.   },
  8463.  
  8464.   /**
  8465.    * Get the em:name property (name of the item)
  8466.    */
  8467.   _rdfGet_name: function(item, property) {
  8468.     return this._getLocalizablePropertyValue(item, property);
  8469.   },
  8470.  
  8471.   /**
  8472.    * Get the em:description property (description of the item)
  8473.    */
  8474.   _rdfGet_description: function(item, property) {
  8475.     return this._getLocalizablePropertyValue(item, property);
  8476.   },
  8477.  
  8478.   /**
  8479.    * Get the em:creator property (creator of the item)
  8480.    */
  8481.   _rdfGet_creator: function(item, property) {
  8482.     return this._getLocalizablePropertyValue(item, property);
  8483.   },
  8484.  
  8485.   /**
  8486.    * Get the em:homepageURL property (homepage URL of the item)
  8487.    */
  8488.   _rdfGet_homepageURL: function(item, property) {
  8489.     return this._getLocalizablePropertyValue(item, property);
  8490.   },
  8491.   
  8492.   _rdfGet_availableUpdateInfo: function(item, property) {
  8493.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8494.     var uri = stringData(this._inner.GetTarget(item, EM_R("availableUpdateInfo"), true));
  8495.     if (uri) {
  8496.       uri = escapeAddonURI(this.getItemForID(id), uri, this);
  8497.       return EM_L(uri);
  8498.     }
  8499.     return null;
  8500.   },
  8501.  
  8502.   /**
  8503.    * Get the em:isDisabled property. This will be true if the item has a
  8504.    * appDisabled or a userDisabled property that is true or OP_NEEDS_ENABLE.
  8505.    */
  8506.   _rdfGet_isDisabled: function(item, property) {
  8507.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8508.     if (this.getItemProperty(id, "userDisabled") == "true" ||
  8509.         this.getItemProperty(id, "appDisabled") == "true" ||
  8510.         this.getItemProperty(id, "userDisabled") == OP_NEEDS_ENABLE ||
  8511.         this.getItemProperty(id, "appDisabled") == OP_NEEDS_ENABLE)
  8512.       return EM_L("true");
  8513.     return EM_L("false");
  8514.   },
  8515.  
  8516.   _rdfGet_addonID: function(item, property) {
  8517.     var id = this._inner.GetTarget(item, EM_R("downloadURL"), true) ? item.Value :
  8518.                                                                       stripPrefix(item.Value, PREFIX_ITEM_URI);
  8519.     return EM_L(id);
  8520.   },
  8521.  
  8522.   /**
  8523.    * Get the em:updateable property - this specifies whether the item is
  8524.    * allowed to be updated
  8525.    */
  8526.   _rdfGet_updateable: function(item, property) {
  8527.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8528.     var opType = this.getItemProperty(id, "opType");
  8529.     if (opType != OP_NONE || this.getItemProperty(id, "appManaged") == "true")
  8530.       return EM_L("false");
  8531.  
  8532.     if (getPref("getBoolPref", (PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, id), false)) == true)
  8533.       return EM_L("false");
  8534.  
  8535.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8536.     if (!installLocation || !installLocation.canAccess)
  8537.       return EM_L("false");
  8538.  
  8539.     return EM_L("true");
  8540.   },
  8541.  
  8542.   /**
  8543.    * See nsIRDFDataSource.idl
  8544.    */
  8545.   GetTarget: function(source, property, truthValue) {
  8546.     if (!source)
  8547.       return null;
  8548.  
  8549.     var target = null;
  8550.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8551.     if (getter in this)
  8552.       target = this[getter](source, property);
  8553.  
  8554.     return target || this._inner.GetTarget(source, property, truthValue);
  8555.   },
  8556.  
  8557.   /**
  8558.    * Gets an enumeration of values of a localizable property. Install Manifests
  8559.    * are generally only in one language, however an item can customize by
  8560.    * providing localized prefs in the form:
  8561.    *
  8562.    *    extensions.{GUID}.[contributor].1
  8563.    *    extensions.{GUID}.[contributor].2
  8564.    *    extensions.{GUID}.[contributor].3
  8565.    *    ...
  8566.    *
  8567.    * to specify localized text for each of these properties.
  8568.    */
  8569.   _getLocalizablePropertyValues: function(item, property) {
  8570.     // These are localizable properties that a language pack supplied by the
  8571.     // Extension may override.
  8572.     var values = [];
  8573.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/,
  8574.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) +
  8575.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8576.     var i = 0;
  8577.     while (true) {
  8578.       try {
  8579.         var value = gPref.getComplexValue(prefName + "." + ++i,
  8580.                                           Ci.nsIPrefLocalizedString);
  8581.         if (value.data)
  8582.           values.push(EM_L(value.data));
  8583.       }
  8584.       catch (e) {
  8585.         try {
  8586.           var value = gPref.getComplexValue(prefName,
  8587.                                             Ci.nsIPrefLocalizedString);
  8588.           if (value.data)
  8589.             values.push(EM_L(value.data));
  8590.         }
  8591.         catch (e) {
  8592.         }
  8593.         break;
  8594.       }
  8595.     }
  8596.     if (values.length > 0)
  8597.       return values;
  8598.  
  8599.     var localized = findClosestLocalizedResource(this._inner, item);
  8600.     if (localized) {
  8601.       var targets = this._inner.GetTargets(localized, property, true);
  8602.       while (targets.hasMoreElements())
  8603.         values.push(targets.getNext());
  8604.       return values;
  8605.     }
  8606.     return null;
  8607.   },
  8608.  
  8609.   /**
  8610.    * Get the em:developer property (developers of the extension)
  8611.    */
  8612.   _rdfGets_developer: function(item, property) {
  8613.     return this._getLocalizablePropertyValues(item, property);
  8614.   },
  8615.  
  8616.   /**
  8617.    * Get the em:translator property (translators of the extension)
  8618.    */
  8619.   _rdfGets_translator: function(item, property) {
  8620.     return this._getLocalizablePropertyValues(item, property);
  8621.   },
  8622.  
  8623.   /**
  8624.    * Get the em:contributor property (contributors to the extension)
  8625.    */
  8626.   _rdfGets_contributor: function(item, property) {
  8627.     return this._getLocalizablePropertyValues(item, property);
  8628.   },
  8629.  
  8630.   /**
  8631.    * See nsIRDFDataSource.idl
  8632.    */
  8633.   GetTargets: function(source, property, truthValue) {
  8634.     if (!source)
  8635.       return null;
  8636.  
  8637.     var ary = null;
  8638.     var propertyName = stripPrefix(property.Value, PREFIX_NS_EM);
  8639.     var getter = "_rdfGets_" + propertyName;
  8640.     if (getter in this)
  8641.       ary = this[getter](source, property);
  8642.     else {
  8643.       // The template builder calls GetTargets when single value properties
  8644.       // are used in a triple.
  8645.       getter = "_rdfGet_" + propertyName;
  8646.       if (getter in this)
  8647.         ary = [ this[getter](source, property) ];
  8648.     }
  8649.  
  8650.     return ary ? new ArrayEnumerator(ary)
  8651.                : this._inner.GetTargets(source, property, truthValue);
  8652.   },
  8653.  
  8654.   Assert: function(source, property, target, truthValue) {
  8655.     this._inner.Assert(source, property, target, truthValue);
  8656.   },
  8657.  
  8658.   Unassert: function(source, property, target) {
  8659.     this._inner.Unassert(source, property, target);
  8660.   },
  8661.  
  8662.   Change: function(source, property, oldTarget, newTarget) {
  8663.     this._inner.Change(source, property, oldTarget, newTarget);
  8664.   },
  8665.  
  8666.   Move: function(oldSource, newSource, property, target) {
  8667.     this._inner.Move(oldSource, newSource, property, target);
  8668.   },
  8669.  
  8670.   HasAssertion: function(source, property, target, truthValue) {
  8671.     if (!source || !property || !target)
  8672.       return false;
  8673.  
  8674.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8675.     if (getter in this)
  8676.       return this[getter](source, property) == target;
  8677.     return this._inner.HasAssertion(source, property, target, truthValue);
  8678.   },
  8679.  
  8680.   _observers: [],
  8681.   AddObserver: function(observer) {
  8682.     for (var i = 0; i < this._observers.length; ++i) {
  8683.       if (this._observers[i] == observer)
  8684.         return;
  8685.     }
  8686.     this._observers.push(observer);
  8687.     this._inner.AddObserver(observer);
  8688.   },
  8689.  
  8690.   RemoveObserver: function(observer) {
  8691.     for (var i = 0; i < this._observers.length; ++i) {
  8692.       if (this._observers[i] == observer)
  8693.         this._observers.splice(i, 1);
  8694.     }
  8695.     this._inner.RemoveObserver(observer);
  8696.   },
  8697.  
  8698.   ArcLabelsIn: function(node) {
  8699.     return this._inner.ArcLabelsIn(node);
  8700.   },
  8701.  
  8702.   ArcLabelsOut: function(source) {
  8703.     return this._inner.ArcLabelsOut(source);
  8704.   },
  8705.  
  8706.   GetAllResources: function() {
  8707.     return this._inner.GetAllResources();
  8708.   },
  8709.  
  8710.   IsCommandEnabled: function(sources, command, arguments) {
  8711.     return this._inner.IsCommandEnabled(sources, command, arguments);
  8712.   },
  8713.  
  8714.   DoCommand: function(sources, command, arguments) {
  8715.     this._inner.DoCommand(sources, command, arguments);
  8716.   },
  8717.  
  8718.   GetAllCmds: function(source) {
  8719.     return this._inner.GetAllCmds(source);
  8720.   },
  8721.  
  8722.   hasArcIn: function(node, arc) {
  8723.     return this._inner.hasArcIn(node, arc);
  8724.   },
  8725.  
  8726.   hasArcOut: function(source, arc) {
  8727.     return this._inner.hasArcOut(source, arc);
  8728.   },
  8729.  
  8730.   beginUpdateBatch: function() {
  8731.     return this._inner.beginUpdateBatch();
  8732.   },
  8733.  
  8734.   endUpdateBatch: function() {
  8735.     return this._inner.endUpdateBatch();
  8736.   },
  8737.  
  8738.   /**
  8739.    * See nsIRDFRemoteDataSource.idl
  8740.    */
  8741.   get loaded() {
  8742.     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  8743.   },
  8744.  
  8745.   Init: function(uri) {
  8746.   },
  8747.  
  8748.   Refresh: function(blocking) {
  8749.   },
  8750.  
  8751.   Flush: function() {
  8752.     // For some operations we block repeated flushing until all operations
  8753.     // are complete to reduce file accesses that can trigger bug 431065
  8754.     if (!gAllowFlush) {
  8755.       gDSNeedsFlush = true;
  8756.       return;
  8757.     }
  8758.     if (this._inner instanceof Ci.nsIRDFRemoteDataSource)
  8759.       this._inner.Flush();
  8760.   },
  8761.  
  8762.   FlushTo: function(uri) {
  8763.   },
  8764.  
  8765.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIRDFDataSource,
  8766.                                          Ci.nsIRDFRemoteDataSource])
  8767. };
  8768.  
  8769. function UpdateItem () {}
  8770. UpdateItem.prototype = {
  8771.   /**
  8772.    * See nsIUpdateService.idl
  8773.    */
  8774.   init: function(id, version, installLocationKey, minAppVersion, maxAppVersion,
  8775.                  name, downloadURL, xpiHash, iconURL, updateURL, updateKey, type,
  8776.                  targetAppID) {
  8777.     this._id                  = id;
  8778.     this._version             = version;
  8779.     this._installLocationKey  = installLocationKey;
  8780.     this._minAppVersion       = minAppVersion;
  8781.     this._maxAppVersion       = maxAppVersion;
  8782.     this._name                = name;
  8783.     this._downloadURL         = downloadURL;
  8784.     this._xpiHash             = xpiHash;
  8785.     this._iconURL             = iconURL;
  8786.     this._updateURL           = updateURL;
  8787.     this._updateKey           = updateKey;
  8788.     this._type                = type;
  8789.     this._targetAppID         = targetAppID;
  8790.   },
  8791.  
  8792.   /**
  8793.    * See nsIUpdateService.idl
  8794.    */
  8795.   get id()                { return this._id;                },
  8796.   get version()           { return this._version;           },
  8797.   get installLocationKey(){ return this._installLocationKey;},
  8798.   get minAppVersion()     { return this._minAppVersion;     },
  8799.   get maxAppVersion()     { return this._maxAppVersion;     },
  8800.   get name()              { return this._name;              },
  8801.   get xpiURL()            { return this._downloadURL;       },
  8802.   get xpiHash()           { return this._xpiHash;           },
  8803.   get iconURL()           { return this._iconURL            },
  8804.   get updateRDF()         { return this._updateURL;         },
  8805.   get updateKey()         { return this._updateKey;         },
  8806.   get type()              { return this._type;              },
  8807.   get targetAppID()       { return this._targetAppID;       },
  8808.  
  8809.   /**
  8810.    * See nsIUpdateService.idl
  8811.    */
  8812.   get objectSource() {
  8813.     return { id                 : this._id,
  8814.              version            : this._version,
  8815.              installLocationKey : this._installLocationKey,
  8816.              minAppVersion      : this._minAppVersion,
  8817.              maxAppVersion      : this._maxAppVersion,
  8818.              name               : this._name,
  8819.              xpiURL             : this._downloadURL,
  8820.              xpiHash            : this._xpiHash,
  8821.              iconURL            : this._iconURL,
  8822.              updateRDF          : this._updateURL,
  8823.              updateKey          : this._updateKey,
  8824.              type               : this._type,
  8825.              targetAppID        : this._targetAppID
  8826.            }.toSource();
  8827.   },
  8828.  
  8829.   classDescription: "Update Item",
  8830.   contractID: "@mozilla.org/updates/item;1",
  8831.   classID: Components.ID("{F3294B1C-89F4-46F8-98A0-44E1EAE92518}"),
  8832.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateItem])
  8833. };
  8834.  
  8835. var gEmSingleton = null;
  8836. var EmFactory = {
  8837.   createInstance: function(outer, iid) {
  8838.     if (outer != null)
  8839.       throw Cr.NS_ERROR_NO_AGGREGATION;
  8840.  
  8841.     if (!gEmSingleton)
  8842.       gEmSingleton = new ExtensionManager();
  8843.     return gEmSingleton.QueryInterface(iid);
  8844.   }
  8845. };
  8846.  
  8847. function DatasourceModule() {}
  8848. DatasourceModule.prototype = {
  8849.   classDescription: "Extension Manager Data Source",
  8850.   contractID: "@mozilla.org/rdf/datasource;1?name=extensions",
  8851.   classID: Components.ID("{69BB8313-2D4F-45EC-97E0-D39DA58ECCE9}"),
  8852.   _xpcom_factory: {
  8853.     createInstance: function() Cc[ExtensionManager.prototype.contractID].
  8854.                                getService(Ci.nsIExtensionManager).datasource
  8855.   }
  8856. };
  8857.  
  8858.  
  8859. function NSGetModule(compMgr, fileSpec)
  8860.   XPCOMUtils.generateModule([ExtensionManager, DatasourceModule, UpdateItem]);
  8861.  
  8862.